I have data that needs to be set differently in the same for loop

load('elevation_data');
E = elevation_data;
[NR,NC] = size(E);
n = 1;
fprintf(' Peak # J-coordinate K-coordinate Elevation \n \n')
for j = 2:(NR-1)
for k = 2:(NC-1)
if E(j,k) >= E(j-1,k-1)&& E(j,k) >= E(j-1,k)&& E(j,k) >= E(j-1,k+1)&& E(j,k) >= E(j,k-1)&& E(j,k) >= E(j,k+1)&& E(j,k) >= E(j+1,k-1)&& E(j,k)>= E(j+1,k)&& E(j,k)>= E(j+1,k+1)
fprintf(' %g %g %g %g \n',n,j,k,E(j,k))
end
end
end
fprintf('Valley # J-coordinate K-coordinate Elevation \n \n')
for j = 2:(NR-1)
for k = 2:(NC-1)
if E(j,k) <= E(j-1,k-1)&& E(j,k) <= E(j-1,k)&& E(j,k) <= E(j-1,k+1)&& E(j,k) <= E(j,k-1)&& E(j,k) <= E(j,k+1)&& E(j,k) <= E(j+1,k-1)&& E(j,k)<= E(j+1,k)&& E(j,k)<= E(j+1,k+1)
fprintf(' %g %g %g %g \n',n,j,k,E(j,k))
end
end
end
This is my code currently. It runs through fine but I'm having trouble setting the variable for the peak or valley number.
>> Peaks_and_Valleys
Peak # J-coordinate K-coordinate Elevation
1 40 43 3.77535
1 50 72 3.5879
1 77 50 8.09256
Valley # J-coordinate K-coordinate Elevation
1 24 54 -6.54186
1 54 28 -3.04738
1 56 55 -0.0604875
This is the answer but i need it to return with the peak and valley numbers to be 1 through 3.

Answers (1)

You never increment your n within the loop. You obviously need a different variable to keep track of the peaks and valleys, I suggest npeaks and nvalleys. Then, within your if, after the fprintf you simply increase the respective variable.
Note that your if statement can be greatly simplified using vectorised comparison:
if all(E(j,k) >= E(j-1:j+1, k-1:k+1)) %compare E(j,k) to the 3x3 surrounding block
fprintf('\t%g\t%g\t%g\t%g\n', npeaks, j, k, E(j, k));
npeaks = npeaks + 1;
end
%similar code for valleys

Categories

Find more on MATLAB in Help Center and File Exchange

Tags

Asked:

on 9 Nov 2015

Edited:

on 9 Nov 2015

Community Treasure Hunt

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

Start Hunting!