Clear Filters
Clear Filters

Issues in For loop

2 views (last 30 days)
vivek narayanan
vivek narayanan on 23 Jun 2021
Edited: Joseph Cheng on 23 Jun 2021
Hi All,
I ma facing issues while reading data and saving in to desired fashion. Here is an example, I need to save the temperature and salinity from a large dataset in every 120th raw for which i wrote the code as shown below.....is there any error? as I am recieving the entire data filed instead of every 120th one....
for i=1:38976;
if(j==120);
if(temp(i)> 0 && temp(i) < 30 );
temp(i)=temp(i) ;
else
temp(i)=NaN;
end
if(sal(i)> 30 && sal(i)< 42);
sal(i)=sal(i);
else
sal(i)=NaN;
end
j=1;
else
j=j+1;
end
end

Accepted Answer

Joseph Cheng
Joseph Cheng on 23 Jun 2021
Edited: Joseph Cheng on 23 Jun 2021
if we break down your for loop:
for i=1:38976;
%this if statement will be done if j==120
%an okay statement here but you can do this with mod(i,120)==0 as you
%already have a counter
if(j==120);
if(temp(i)> 0 && temp(i) < 30 );
temp(i)=temp(i); %this isn't doing anything as its over writting itself
else
temp(i)=NaN; %changes i to nan... okay statement but its only working on j==120
end
%temp statements apply to the sal if statement so its sal
%portion has been cut out.
j=1; %reset j to 1.
else
j=j+1; %increment j if j~=120
end
end
so since you're not stashing the items into another array when the index is a multiple of 120 you'll obviously get the whole array back as you did nothing but look at the input array and make it a Nan if the temp is between 0 and 30.
you can quickly retrieve the data your input variables through indexing like
temp_120=temp(120:120:end); % as that'll start with 120 increment by 120 till the end of the array.
temp_120(~(temp_120>0 & temp_120<30))=Nan; %change the items which are not between 0 and 30 to nans
like here:
x = [ 1 2 3 4 5 10 2 3 4 5 18 2 3];
x_4 = x(2:4:end)
x_4 =
2 4 10 3 5 2
x_4(~(x_4>3 & x_4<10))=nan
x_4 =
NaN 4 NaN NaN 5 NaN

More Answers (1)

Alan Stevens
Alan Stevens on 23 Jun 2021
Have you intialised j (i.e. set j = 1;) before going into the for i = 1:38976 loop?

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!