Store mxn matrix within a for loop
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
How can I store results of a for loop when one iteration gives m x n matrix and not a 1 x n matrix?
a = rand(20,12);
for k=length(a)
store_this = reshape((a(k,:)), 3, [])';
end
**EDIT
The sample code I wanted to share is as follows, and the one above is wrong as pointed out :)
a = rand(20,12);
for k=1:size(a,1)
store_this = reshape((a(k,:)), 3, [])';
end
2 Kommentare
Rik
am 19 Jul. 2022
Your loop is confusing.
Did you intend to have a single iteration?
Did you intend to use max(size(a))? Judging from your indexing, you may have wanted size(a,1) instead.
If you would have multiple iterations, that would mean your array gets overwritten every time. Is that intentional?
Akzeptierte Antwort
Rik
am 19 Jul. 2022
Bearbeitet: Rik
am 19 Jul. 2022
I'm not sure this is the optimal way to do it, but this does what you explain by using a cell array as an intermediary step.
a = rand(20,12);
store_this=cell(1,size(a,1));
for k=1:size(a,1)
store_this{k} = reshape((a(k,:)), 3, [])';
end
store_this=vertcat(store_this{:})
In this case your entire loop can be replaced by a single line:
x=reshape(a.',3,[]).';
isequal(x,store_this),store_this
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!