Issues in For loop

조회 수: 1 (최근 30일)
vivek narayanan
vivek narayanan 2021년 6월 23일
편집: Joseph Cheng 2021년 6월 23일
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

채택된 답변

Joseph Cheng
Joseph Cheng 2021년 6월 23일
편집: Joseph Cheng 2021년 6월 23일
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

추가 답변 (1개)

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by