Keep new array from overwriting in loop
6 次查看(过去 30 天)
显示 更早的评论
Hi everyone, I have a problem in my code that is overwriting my new array every time the for loop iterates. I want it to add on to the bottom, so I have all the files that work with the 'if' statement. I would like 'inflowsoundings' to keep all the 'inputfilename's that run through correctly but it currently overwrites the values. Here is my code with the first loop and the problem is in the last for loop:
for i = 1:size(Tor_Time,1)
midpt_lat(i) = Tor_Time(i,20);
midpt_lon(i) = 180 + (180-abs(Tor_Time(i,21)));
%Names midpoints of storm locations (also converts West longitudes to East longitudes)
for j = 1:size(Stat_Loc,1)
middistance_deg(i,j)=distance(midpt_lat(i),midpt_lon(i),Lat(j),Long(j));
%
middistance(i,j)=distdim(middistance_deg(i,j),'deg','km');
end
%Calculates distance from storm to all station locations then converts
%degrees to kilometers
index_400_middist = find(middistance(i,:)<=400.0);
% find indexes stations within 400 km of the midpoint of event
Stat_IDs_400 = Stat_IDs(index_400_middist,3);
% Gives stations that are <= 400km from storm
filename = ['stormID_storm' num2str(i) '_' num2str(Tor_Time(i,3)) '_' num2str(Tor_Time(i,4)) '.mat'];
% Names all stations that are within 400km of each storm in .mat files
% (each storm has a different .mat file)
save(filename,'Stat_IDs_400')
for f = 1:length(Stat_IDs_400)
inputfilename = [num2str(Tor_Time(i,3)),'_',num2str(Tor_Time(i,4)),'_',char(Stat_IDs_400(f)),'.xlsx'];
inputfile = [pwd,'\StormSoundings\',inputfilename];
if exist(inputfile, 'file') == 2
[avgcdt,az] = inflowsector(inputfilename,midpt_lat(i),midpt_lon(i));
else
inputfile;
avgcdt = NaN;
az = NaN;
end
%
if az>=(avgcdt-75) | az<=(avgcdt+75)
inflowsoundings{f,:}=inputfilename; %Tor_Time(1,:);
else
inflowsoundings{f} = NaN;
end
end
% MAKE CAPE CALCULATIONS
end
Any help is greatly appreciated. Thanks!
0 个评论
回答(1 个)
Greg Dionne
2017-3-16
You can try this:
if az>=(avgcdt-75) | az<=(avgcdt+75)
inflowsoundings{end+1}=inputfilename;
end
2 个评论
Greg Dionne
2017-3-17
Then you'll need to initialize it outside the for-loop.
inflowsoundings = cell(1,0)
Then you can assign in your loop.
For example:
>> inflowsoundings = cell(0,1)
inflowsoundings =
0×1 empty cell array
>> inflowsoundings{end+1} = 'alpha'
inflowsoundings =
cell
'alpha'
>> inflowsoundings{end+1} = 'beta'
inflowsoundings =
1×2 cell array
'alpha' 'beta'
>> inflowsoundings{end+1} = 'gamma'
inflowsoundings =
1×3 cell array
'alpha' 'beta' 'gamma'
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Operators and Elementary Operations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!