Saving double without overwriting in nested For loop

6 views (last 30 days)
Hi there,
I'm currently writing a script to take into a bunch of files (known as spotno) and interate through evey second column from 7 up to 48 effectively extracting a variable in the form of 673x21 double called IndividualGaveFinal (subject to change depending on the spotno) for each spotno. The problem I keep facing is that it's only saving IndividualGaveFinal for the final spotno iteration. What's the best way of altering the code to save IndividualGaveFinal for each spotno for summing all the spotno IndividualGaveFinal variables? I've noted that some mathworks community questions similar to this have recommended creating a preallocated array as shown. I've attached the code below:
arraytest=zeros(673,21);
for spotno=1:processedfilenum
for j=7:2:48
channelA=j ;
channelB=channelA+1;
FCSvarname = ['FCS_C' num2str(channelA) num2str(channelB)];
%define and write array to mat that lists: new channel, original channel, start filter time, stop filter time, total num of photons
%opens FCS_C... and sets as individualFCS data
individualFCS = handles.mat.(FCSvarname);
%Same as time but for Gave data for each FCS_C...
individualGave(:,j) = individualFCS.Gave;
GavecolumnsWithAllZeros = all(time == 0);
individualGavefinal=individualGave(:,~GavecolumnsWithAllZeros);
for arraytest = 1:spotno
sprintf('individualGavefinal');
end
end
end
I'm also aware that there's two ways of doing this:
Saving IndividualGaveFinal for each spotno file seperately or in a struct
Saving IndividualGaveFinal for the first spotno file, then adding the second IndividualGaveFinal spotno, and so on...
Any help would be greatly appreciated!!
Thanks in advance.
  1 Comment
Stephen23
Stephen23 on 15 Dec 2019
Edited: Stephen23 on 15 Dec 2019
"'I've noted that some mathworks community questions similar to this have recommended creating a preallocated array as shown."
The code you show does preallocate an array named arraytest:
arraytest=zeros(673,21);
But you never assign anything to it, making that preallocation unused.
Inside the nested loops you completely reallocate this variable (as a loop iterator variable), which means that after the loops' first iteration your preallocated array no longer exists anyway:
for spotno=1:processedfilenum
for j=7:2:48
...
for arraytest = 1:spotno % here you reallocate ARRAYTEST
...
end
end
end
You should probably revise what array preallocation is and look at typical examples of it:

Sign in to comment.

Answers (1)

Anmol Dhiman
Anmol Dhiman on 15 Dec 2019
Assuming the size of all IndividualGaveFinal matrices are same, i.e. 673x21 double. You can use cell array to store the individual matrices. See the below links for more references.
Hope it Helps

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!