Store mxn matrix within a for loop

3 Ansichten (letzte 30 Tage)
Jake
Jake am 19 Jul. 2022
Bearbeitet: Rik am 19 Jul. 2022
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
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?
Jake
Jake am 19 Jul. 2022
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 (?).

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Rik
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{:})
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

Weitere Antworten (0)

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!

Translated by