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

1 Ansicht (letzte 30 Tage)
gamer
gamer am 17 Jun. 2021
Kommentiert: gamer am 17 Jun. 2021
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 Kommentare
SungJun Cho
SungJun Cho am 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 am 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.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

KSSV
KSSV am 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

Weitere Antworten (0)

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by