Save output from for loop without overwriting previous outputs?
You are now following this question
- You will see updates in your followed content feed.
- You may receive emails, depending on your communication preferences.
An Error Occurred
Unable to complete the action because of changes made to the page. Reload the page to see its updated state.
Show older comments
0 votes
Let't say I want to save the output "Qv_maalt" of each iteration to a vector called "Final". Currently I have 10 files for the loop to process, and thus, 10 iterations.
Where do i put the for loop in order to avoid overwriting of the variable "Qv_maalt" at each iteration, and instead write the output of each iteration to the same vector, and thus ending up with a vector of 10 different values.
My current code reads:
close all
files = dir('*.mat');
for file = files'
load([file.name]);
dt = Data1_time_M_airsupply(end);
hold on
midling = ones(1, 1000)/1000;
filtrering = filter(midling,1,Data1_M_airsupply_IIR_Filter);
plot(filtrering)
deltaMass = filtrering(1) - filtrering(end);
Qm = deltaMass / dt;
T = mean(Data1_T_orifice);
tempVektor = [35 30 25 20 15 10 5 0 -5 -10 -15 -20 -25];
densVektor = [1.145 1.164 1.183 1.204 1.225 1.246 1.269 1.292 1.316 1.341 1.367 1.394 1.422];
Rho = interp1(tempVektor, densVektor, T);
Qv_maalt = Qm / Rho;
end
Apologies for lack of brevity.
Thanks in advance!
Accepted Answer
Geoff Hayes
on 21 Mar 2015
Peter - just define the vector Final (you may want to come up with a more descriptive name for it) before entering the for loop and update it at each iteration. Something like
files = dir('*.mat');
Final = zeros(length(files),1);
for k=1:length(files)
load([files(k).name]);
% etc.
Qv_maalt = Qm / Rho;
Final(k) = Qv_maalt;
end
The above assumes that Qv_maalt is a scalar. If it is a vector, then you will need to size Final accordingly. If Qv_maalt is of a different size on each iteration of the loop, then consider using a cell array for Final.
14 Comments
Peter
on 21 Mar 2015
Thanks Geoff. I works!
Angus Horne
on 24 Apr 2019
What do you do when you get the error 'Unable to perform assignment because the left and right sides have a different number of elements' after perfomring this command. I am trying to make all the locs values into an array as below however only seem to storing the final value - is this the source of my problem?
listing = dir('*.bmp');
%check listing is working by whos listing
firstimg = imread(listing(1).name);
Final = zeros(length(listing),1);
for n=1:length(listing)
img = imread([listing(n).name]);
G = img(:,:,2)-firstimg(:,:,2); % take green channel only
G = 255*(G-min(G(:)))/(max(G(:))-min(G(:)));
FG = abs(fftshift(fft2(G)));
imagesc(log(FG));
[X,Y] = meshgrid((1:size(FG,2))-ceil(size(FG,2)/2),(1:size(FG,1))-ceil(size(FG,1)/2));
R = sqrt(X.^2+Y.^2);
rprofile = [];
for r = linspace(2,50,200)
criteria = (R>r-2 & R<r+2);
rv = double(FG(criteria)).*(2-abs(R(criteria)-r));
rprofile = [rprofile,mean(rv(:))];
end
figure; plot(linspace(2,50,200),rprofile)
xlabel('Wavelength')
ylabel('Intensity')
pause(1);
[pks,locs] = findpeaks(rprofile, linspace(2,50,200), 'MinPeakDistance', 47)
pause (1);
Final(n) = (locs);
end
Geoff Hayes
on 24 Apr 2019
Angus - use a cell array instead for the Final array since you may have a different number of peaks (and so locs will have a different length) on each iteration of your loop. What is probably happening here is that on the first iteration of your loop, locs is of length x. Then on the next iteration of your loop, if locs is of a different length, then you will observe this error. Also, you seem to be assuming that locs is a scalar which I don't think you can guarantee:
Final = zeros(length(listing),1);
Angus Horne
on 25 Apr 2019
Thank you Geoff!!
Turbulence Analysis
on 19 Aug 2020
Hi Goeff Hayes,
I have the similar problem, in my below code, the operation output pushes 1x4 values for each iteration, finally it should be saved in output1 matrix as 10 x 4 at the end of the iteration.. But getting below error...
Unable to perform assignment because the left and right sides have a different number of elements.
output1 = zeros(10,4);
for f = 1:1:10
if (f>=1) && (f<=9)
fname_strt = 'B0000' ;
elseif (f>=10) && (f<=99)
fname_strt='B000';
elseif (f>=100) && (f<=999)
fname_strt='B00';
else
fname_strt='B0';
end
fname_end = num2str(f);
fname = strcat(fname_strt,fname_end,'.txt');
A=dlmread(fname,'\t',1,0);
sz = [112 98];
x = reshape(A (:,1),sz);
y = reshape(A (:,2),sz);
u = reshape(A (:,3),sz)';
v = reshape(A (:,4),sz)';
x1 = x(:,1);
y1 = y (1,:)';
output=IDvortex(x1,y1,u,v);
output1(f)= output;
% a= output(:,1);
% b=output(:,2);
% c=output(:,3);
% d=output(:,4);
% output1(f,:) = [a,b,c,d];
end
Geoff Hayes
on 19 Aug 2020
If we can assume that output is always a 1x4 array, then you can replace
output1(f)= output;
with
output1(f, :)= output;
where we use the colon : to indicate all columns of row f.
Turbulence Analysis
on 19 Aug 2020
Thanks Geoff... Yes, output is always 1x4 array. I tried with output1(f, :)
But end up with error
Unable to perform assignment because the size of the left side is 1-by-4 and the size of the right side is
2-by-4.
Geoff Hayes
on 19 Aug 2020
The error message suggests that output is a 2x4 array and not a 1x4 array. Try using the debugger to step through the code to confirm that this is true. Or look closely at your IDVortex function and see why it might return a 2x4 array.
Turbulence Analysis
on 19 Aug 2020
Goeff, Yes, you are correct. I have checked.. Sometimes it pushes 2 x 4.. May I know how to handle if size is not uniform..??
Geoff Hayes
on 19 Aug 2020
Do you need output1 to be a matrix or can it be a cell array? Do you still need to know that the (for example) second iteration produced a 2x4 array? I don't know what you will be doing with your output but sometimes, when your data is of different dimensions, you would just store it in a cell array like
output1 = cell(10,1); % <--- initialize as cell array
for f = 1:1:10
if (f>=1) && (f<=9)
fname_strt = 'B0000' ;
elseif (f>=10) && (f<=99)
fname_strt='B000';
elseif (f>=100) && (f<=999)
fname_strt='B00';
else
fname_strt='B0';
end
fname_end = num2str(f);
fname = strcat(fname_strt,fname_end,'.txt');
A=dlmread(fname,'\t',1,0);
sz = [112 98];
x = reshape(A (:,1),sz);
y = reshape(A (:,2),sz);
u = reshape(A (:,3),sz)';
v = reshape(A (:,4),sz)';
x1 = x(:,1);
y1 = y (1,:)';
output=IDvortex(x1,y1,u,v);
output1{f} = output; % <--- add array to cell array
end
Turbulence Analysis
on 19 Aug 2020
I would perfer a matrix.. Actually, the function IDvortex will retrun vortices position (x, y) - 1, 2 column and its size and strength in thrird and fourth column. Some file might have two vortices present in a single one, that's why it throws 2x4 array instead of 1X4.
My intension is to plot file number Versus ''y'' position (i.e. 2 column).. Here there are 10 input files. For example, in the first input file, where ''y'' locates. It would be great if could shed some light on this.. I have attaced the generated structure file for your refrence...
Geoff Hayes
on 19 Aug 2020
well you can convert the cell array to a matrix after you have finished the for loop
output1AsMatrix = cell2mat(output1);
Geoff Hayes
on 19 Aug 2020
Turbulence Analysis answer moved here
Yes, I have tried that got a attached mat file, here as you can see I have got 13x4 matrix for 10 files, actually row 3 and 4 belongs to same input file B00003.. Is there any possibility to group this...
Geoff Hayes
on 19 Aug 2020
Group it how? How would you want to combine or group the two?
More Answers (0)
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)