Storing values from nested FOR loop (array only saves last run of results)
448 views (last 30 days)
Hi guys, have tried searching but can't find anything to help, maybe my problem is too simple! lol Anyway, I'm running a nested FOR loop, but the array I save my results to only keeps the last "run" of results. Can someone please help me to store/concatenate the results in a single array? EG the resultant array should have 12 rows, not 4. with column one going 1,2,3,4,1,2,3,4,1,2,3,4 and column two going 10,10,10,10,20,20,20,20,30,30,30,30.
Cheers in advance! (first line currently commented out as the last 8 rows stay zero at the minute)
%tableA = zeros(12,2);
P.S. this isn't the real code I'm using, but a dumbed down version just so I can get the correct syntax to use to apply to the bigger problem! Cheers.
More Answers (4)
dpb on 6 Mar 2014
As this is clearly early learning, let's go with a hint-based approach rather than just throwing out an answer -- might make it more beneficial to discover the answer sorta' on your own...
%tableA = zeros(12,2);
1) preallocating is a_good_thing (tm) so bring that back out of retirement but -- first, for ease use a variable for the upper limit on the two loops so you can modify them and easily compute the size of the array needed--
nr=4; % rows
nc=3; % columns
table=zeros(nr,nc); % preallocate
2) NB: that answerA is invariant with j so move it outside the inner loop--no sense doing stuff over and over that is the same answer every time--
answerA=i*1; % of course the '*1' isn't needed but it's tutorial, so ok...
3) Now to the nub of your ? --
AnswerB=j*10; % NB: this doesn't give what you say you want, either...
table(?,?) = ???
Walk thru the steps and follow what i is each pass -- it should be apparent what the next row index should be; what computation would generate that?
After that, then look at how to get the indices for the two values in the proper columns -- it's a similar idea. Or, of course, instead of building a vector to store two at a time, store the individual i,j elements in their correct location when generate them is more direct.
4) Rethink the whole process and see if you cannot actually compute the whole thing in a vectorized form and eschew the loops entirely. That's "the Matlab way".
Chew on that a while and then come back... :)
Sawan Kumar Jindal on 3 Oct 2016
Edited: Sawan Kumar Jindal on 3 Oct 2016
The first thing to do is assign zero value to each location of the matrix and then, use for loops to store the value. You have not initialised the memory for all the locations.