Store mxn matrix within a for loop

2 次查看(过去 30 天)
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 个评论
Rik
Rik 2022-7-19
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?
Jake
Jake 2022-7-19
You're right! The sample code I've shared was wrong. I've corrected it in the question too.
As you see, each iteration creates 4 x 3 matrix under store_this. What I'm trying is to store those 4 x 3 matrices in each iteration one after the other. So for instance, store_this would look like a 8 x 3 matrix after its second iteration. I'm not sure if that's feasible, or detailed enough (?).

请先登录,再进行评论。

采纳的回答

Rik
Rik 2022-7-19
编辑:Rik 2022-7-19
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{:})
store_this = 80×3
0.2288 0.3095 0.1840 0.9412 0.6852 0.0284 0.5210 0.5932 0.5208 0.1174 0.2460 0.1937 0.3876 0.2077 0.4256 0.7620 0.6441 0.3932 0.8775 0.5043 0.9992 0.8888 0.4054 0.3534 0.4653 0.9296 0.3296 0.1698 0.7805 0.6041
In this case your entire loop can be replaced by a single line:
x=reshape(a.',3,[]).';
isequal(x,store_this),store_this
ans = logical
1
store_this = 80×3
0.2288 0.3095 0.1840 0.9412 0.6852 0.0284 0.5210 0.5932 0.5208 0.1174 0.2460 0.1937 0.3876 0.2077 0.4256 0.7620 0.6441 0.3932 0.8775 0.5043 0.9992 0.8888 0.4054 0.3534 0.4653 0.9296 0.3296 0.1698 0.7805 0.6041

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by