How to save vector output from for loop?

For i=1:10 A=[i i+1 i+2; i+1 i i+1; i+2 i+1 i]; end
Now I want to make a new matrix Such that it's first element is the output of loop's eleration and so on.
Like this B = [A1 A2 A3.....A10 ]

 Akzeptierte Antwort

madhan ravi
madhan ravi am 30 Mär. 2019

1 Stimme

Save it as a 3D matrix:
A=zeros(3,3,10); % pre-allocate
for k = 1:10
A(:,:,k)=[k k+1 k+2; k+1 k k+1; k+2 k+1 k];
end

3 Kommentare

Without loop:
B=[0 1 2;1 0 1;2 1 0]+(reshape(1:10,1,1,numel(1:10))); % since to 2016b
B=bsxfun(@plus,[0 1 2;1 0 1;2 1 0],(reshape(1:10,1,1,numel(1:10)))); % prior to 2016b
Areeb Siraj
Areeb Siraj am 30 Mär. 2019
And if it has to be a 2D Matrix. Then
B=bsxfun(@plus,[0 1 2;1 0 1;2 1 0],(reshape(1:10,1,1,numel(1:10))));
reshape(B,3,[])

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Stephen23
Stephen23 am 31 Mär. 2019
Bearbeitet: Stephen23 am 31 Mär. 2019

2 Stimmen

Much simpler without a loop:
>> A = toeplitz(1:3)+reshape(1:9,1,1,[])
A(:,:,1) =
1 2 3
2 1 2
3 2 1
(:,:,2) =
2 3 4
3 2 3
4 3 2
A(:,:,3) =
3 4 5
4 3 4
5 4 3
... more pages here
A(:,:,9) =
9 10 11
10 9 10
11 10 9
A(:,:,10) =
10 11 12
11 10 11
12 11 10
For MATLAB versions prior to R2016b replace the + with bsxfun and plus.

2 Kommentare

Areeb Siraj
Areeb Siraj am 31 Mär. 2019
Thank you I got it.
Stephen23
Stephen23 am 31 Mär. 2019
@Areeb Siraj: then you can vote for my answer too :)

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Produkte

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by