Create a matrix out of single values if a for loop?

1 view (last 30 days)
Hello,
is it possible to create a 1xF matrix in a for loop out of single values?
n = 2;
r = 0.5;
a = 10;
b = 5;
p = [r + (a-2*r)*rand(n,1),r + (b-2*r)*rand(n,1 )];
for i = 1:n
for j = i:n
if i == j
continue
end
H = (norm(p(i,:)-p(j,:))<=2*r)
end
end
  5 Comments
SungJun Cho
SungJun Cho on 17 Jun 2021
You should preallocate H as a matrix and save each values into your matrix. For example,
% ...
H = zeros(n,n);
for i = 1:n
for j = i:n
% ...
H(i,j) = (norm(p(i,:)-p(j,:))<=2*r)
end
end
gamer
gamer on 17 Jun 2021
I tried it like that but it just gives me again 3 matrices back instead of one
r = 0.5; a = 0; b = 5; n = 3
p=[r + (a-2*r)*rand(n,1),r + (b-2*r)*rand(n,1)];
H = zeros(1,((n-1)*n)/2 )
for i = 1:n
for j = i:n
if i == j
continue
end
H(1,((n-1)*n)/2) = (norm(p(i,:)-p(j,:)))
end
end
I want the norm of (p(1,:) - p(2,:), p(1,:) - p(3,:) and p(2,:) - p(3,:) in one matrix. This is just an example for n = 3.

Sign in to comment.

Accepted Answer

KSSV
KSSV on 17 Jun 2021
r = 0.5; a = 0; b = 5;
n = 3 ;
p=[r + (a-2*r)*rand(n,1),r + (b-2*r)*rand(n,1)];
H = zeros(1,[]) ;
count = 0 ;
for i = 1:n
for j = i:n
if i == j
continue
end
count = count+1 ;
H(1,count) = (norm(p(i,:)-p(j,:)))
end
end

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!