How do I save my data from each loop iteration into a single matrix?

18 views (last 30 days)
I am trying to save each calculated variables from each run of the loop into an output file.
I have the following code, however it overwrites the data for each loop so I am only left with the final iteration's data in the end.
for i=[1:no_lines]
x= -image_width/2 + (i-1)*d_x;
xdc_center_focus (emit_aperture, [x 0 0]);
xdc_focus (emit_aperture, 0, [x 0 z_focus]);
xdc_center_focus (receive_aperture, [x 0 0]);
xdc_focus (receive_aperture, focus_times, [x*ones(Nf,1), zeros(Nf,1), focal_zones]);
N_pre = round(x/(width+kerf) + N_elements/2 - N_active/2);
N_post = N_elements - N_pre - N_active;
apo_vector=[zeros(1,N_pre) apo zeros(1,N_post)];
xdc_apodization (emit_aperture, 0, apo_vector);
xdc_apodization (receive_aperture, 0, apo_vector);
[rf_data, tstart]=calc_scat(emit_aperture, receive_aperture, phantom_positions, phantom_amplitudes); %output to save
save(sprintf('rft%04d.mat',k),'rf_data','tstart')
x = x + d_x; %adds to the x for the next iteration
end

Answers (2)

Shubham Gupta
Shubham Gupta on 10 Dec 2018
Edited: Shubham Gupta on 10 Dec 2018
save(sprintf('rft%04d.mat',k),'rf_data','tstart')
There should be " i " in place "k" in the above line and you will be able to save 'rf_data' and 't_start' as rtf0001, rtf0002 and so on. I hope this answers your question
  1 Comment
devon foggio
devon foggio on 10 Dec 2018
Thank you! This changed worked and allows for saving of each data set after each iteration- however is there a way to save and add into one total matrix output from the loop?

Sign in to comment.


Star Strider
Star Strider on 10 Dec 2018
Without knowing what size your variables ‘rf_data’ and ‘tstart’ are, the easiest way would be to save them to cell arrays, then (if necessary) convert the cell arrays to numeric arrays after the loop, and save them then:
[rf_data{i}, tstart{i}]=calc_scat(emit_aperture, ...
. . .
end
save(sprintf('rft%04d.mat',i),'rf_data','tstart')
This will create the file name using the last value of ‘i’. Change (or delete) the sprintf call if you want to save it with one specific file name.

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!