Creating matrix outside for loop

I need to create a matrix of variables and have the current code below. Is there anyway to do this without a for loop?
x = 0:.1:1;
y = 0:.1:1;
for i = 1:length(x)
for j = 1:length(y)
x2(i,j) = x(i);
y2(i,j) = y(j);
end
end

 採用された回答

Star Strider
Star Strider 2017 年 2 月 19 日
編集済み: Star Strider 2017 年 2 月 19 日

0 投票

Try this:
x2 = y'*ones(size(x));
y2 = ones(size(y'))*x;
EDIT
The R2016b multiplication automatically does the expansion. Previous versions would require bsxfun calls:
x2 = bsxfun(@times, y', ones(size(x)));
y2 = bsxfun(@times, ones(size(y')), x);

5 件のコメント

m13
m13 2017 年 2 月 19 日
Thank you! Now I have another question along the same lines. Is there a way to simplify the code below. Both x1 and y1 will change in the for loop.
for i = 2:length(x)-1
for j = 2:length(y)-1
x1 = x(i);
y1 = y(j);
Star Strider
Star Strider 2017 年 2 月 19 日
My pleasure!
MATLAB vectorised addressing will work here. You don’t need the loops.
Providing the dimensions are appropriate:
i = 2:length(x)-1
j = 2:length(y)-1
x1 = x(i);
y1 = y(j);
For example:
x = 11:17
i = 2:length(x)-1;
xp = x(i)
x =
11 12 13 14 15 16 17
xp =
12 13 14 15 16
Akira Agata
Akira Agata 2017 年 2 月 20 日
Another solution for the original question.
x = 0:.1:1;
y = 0:.1:1;
x2 = repmat(x',1,length(y));
y2 = repmat(y,length(x),1);
m13
m13 2017 年 2 月 20 日
Star if I need to use the y1 value in another for loop does this still work? I tried it and now I'm getting the error that the number of elements must be the same. The for loop is:
for k = 1:n
U(k) = sin(y1);
end
Star Strider
Star Strider 2017 年 2 月 20 日
You do not need the loop.
This works:
U = sin(y1);
(I apologise for the delay.)

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

質問済み:

m13
2017 年 2 月 19 日

コメント済み:

2017 年 2 月 20 日

Community Treasure Hunt

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

Start Hunting!

Translated by