how to save every iteration into workspace
12 views (last 30 days)
Show older comments
my code would save just the last iteration.
for c=1:170
name1 = strcat(folder_name1,'/',filesStruct1(c).name);
alpha = (((double(dicomread(name1)).*pi)./(4096)) - (pi./2))
dicomwrite(alpha, (strcat('Results/',filesStruct1(c).name)));
save(mfilename)
end
can you please edit my code so it saves alpha 170 times with 170 different 256*240 matrices thanks in advance
0 Comments
Accepted Answer
Stephen23
on 12 Mar 2018
Edited: Stephen23
on 12 Mar 2018
Use fullfile rather than string concatenation. To store the imported images in a loop simply preallocate a cell array before the loop, and then use indexing:
N = 170;
C = cell(1,N);
for k = 1:N
name = fullfile(folder_name1,filesStruct1(c).name);
alpha = double(dicomread(name1))*pi/4096 - pi/2
dicomwrite(alpha, fullfile('Results',filesStruct1(c).name));
C{k} = alpha;
end
save(mfilename,'C')
3 Comments
dpb
on 12 Mar 2018
Hadn't researched the cell/structure array sufficiently. I had presumed they would be implemented more like a linked list than actual arrays and therefore "not so much" a performance hit. So OP needs to put an allocation step after determining the size in my above answer... :)
More Answers (2)
dpb
on 12 Mar 2018
Edited: dpb
on 12 Mar 2018
n=length(filesStruct1); % presuming filesStruct1 is returned from DIR()
alpha=cell(n,1); % listen to the pundits and preallocate even cell array :)
for c=1:n
name1 = fullfile(folder_name1,filesStruct1(c).name);
alpha{c} = double(dicomread(name1)*pi)/4096 - pi/2;
end
...
NB: the "curlies" {} to create cell array alpha.
Alternatively you could read the first to determine
[r,c]=size(alphaOne); % first in case possibly use differing size arrays
alpha=zeros(r,c,n); % preallocate a 3D array, put each into slice (plane)
alpha(:,:,1)=alphaOne); % save first
clear alphaOne % minor cleanup; don't need any longer
for c=2:n % now do the rest
alpha(:,:,c)= ........
...
This way one has a default double array instead of cell array so can save a dereferencing step in use or, depending on what is to be done, making calculations across the various planes is much simpler if that were to be wanted/required...
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!