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

1 vue (au cours des 30 derniers jours)
gamer
gamer le 17 Juin 2021
Commenté : gamer le 17 Juin 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 commentaires
SungJun Cho
SungJun Cho le 17 Juin 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 le 17 Juin 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.

Connectez-vous pour commenter.

Réponse acceptée

KSSV
KSSV le 17 Juin 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

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by