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

1 回表示 (過去 30 日間)
gamer
gamer 2021 年 6 月 17 日
コメント済み: gamer 2021 年 6 月 17 日
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 件のコメント
SungJun Cho
SungJun Cho 2021 年 6 月 17 日
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 2021 年 6 月 17 日
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.

サインインしてコメントする。

採用された回答

KSSV
KSSV 2021 年 6 月 17 日
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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by