How to save vectors made by a for-end loop?
Show older comments
%I have a .dat called NOAA_DATA. I am trying to plot the sum of a certain column sorted %by each year (1974-2014).
for i = 1974:1:2014
ind_1 = find(NOAA_DATA(:,1) == i,1,'first')
ind_2 = find(NOAA_DATA(:,1) == i,1,'last')
end
Answers (1)
Geoff Hayes
on 25 Nov 2014
Skylar - you could create a vector, outside of the for loop, that would be used to hold all of the first and last indices/appearances for each year. Try the following
% create the 2D year index matrix
yearIndices = zeros(2014-1974+1,2);
for k=1974:1:2014
ind_1 = find(NOAA_DATA(:,1) == i,1,'first');
ind_2 = find(NOAA_DATA(:,1) == i,1,'last');
% if we have found the first index (so non-empty) then we know
% there is a last index too
if ~isempty(ind_1)
yearIndices(k,1) = ind_1;
yearIndices(k,2) = ind_2;
end
end
We create the matrix yearIndices which has two columns for the first appearance/index of the year, and for the last appearance/index of the year. We initialize all elements to zero because if we never find the first and last index for a year, then the ind_1 and ind_2 will be empty and so we can leave the row in the matrix as zeros which correspond to invalid indices (since all MATLAB indices are at least one).
Categories
Find more on Operating on Diagonal Matrices 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!