Store mxn matrix within a for loop
3 views (last 30 days)
Show older comments
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 Comments
Rik
on 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?
Accepted Answer
Rik
on 19 Jul 2022
Edited: Rik
on 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 Comments
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!