Hi I have a for loop. The result of every iteration is a rowvector. I want all rowvectors of the for loop stored as one matrix. Each row is the result of one iteration.
Simplified example:
if true
X= 1:0.1:2;
for i = 1:length(X)
A=4
B= 1:5
Y= A.*X(i)+B
end
end
The end result shoud be an 11 x 5 matrix. Indexing will give errors, so will starting with an empty array.

4 件のコメント

Bob Thompson
Bob Thompson 2019 年 10 月 9 日
What do you mean, 'Indexing will give errors?' What error message are you getting?
I was able to get the result to index just fine.
X= 1:0.1:2;
for i = 1:length(X)
A=4
B= 1:5
Y(i,:)= A.*X(i)+B
end
Mike Mierlo van
Mike Mierlo van 2019 年 10 月 9 日
You Da Man!
I tried Y(i)=A.X(i)+B which was giving me a hard time. The ,: made the difference. Thank you!
Stephen23
Stephen23 2019 年 10 月 9 日
編集済み: Stephen23 2019 年 10 月 9 日
You do not need a loop, just
>> A*X(:) + B % for MATLAB >= R2016b
Or for earlier versions use bsxfun:
>> bsxfun(@plus,A*X(:),B)
ans =
5.0000 6.0000 7.0000 8.0000 9.0000
5.4000 6.4000 7.4000 8.4000 9.4000
5.8000 6.8000 7.8000 8.8000 9.8000
6.2000 7.2000 8.2000 9.2000 10.2000
6.6000 7.6000 8.6000 9.6000 10.6000
7.0000 8.0000 9.0000 10.0000 11.0000
7.4000 8.4000 9.4000 10.4000 11.4000
7.8000 8.8000 9.8000 10.8000 11.8000
8.2000 9.2000 10.2000 11.2000 12.2000
8.6000 9.6000 10.6000 11.6000 12.6000
9.0000 10.0000 11.0000 12.0000 13.0000
Mike Mierlo van
Mike Mierlo van 2019 年 10 月 9 日
For the simplified version this is OK. But in my sophisticated version is A and B an array too, so I think in that case an loop fits best.

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

 採用された回答

meghannmarie
meghannmarie 2019 年 10 月 9 日
編集済み: meghannmarie 2019 年 10 月 9 日

1 投票

if true
X= 1:0.1:2;
A = 4;
B = 1:5;
Y = nan(length(X),length(B));
for i = 1:length(X)
Y(i,:) = A.*X(i)+B;
end
end

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File Exchange で Loops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by