How do I create two MATLAB for loops

2 views (last 30 days)
Johanna Huber
Johanna Huber on 10 Aug 2022
Commented: Jeffrey Clark on 10 Aug 2022
Hi,
I am new to MATLAB and my loops don't work out the way I want them to.
I have a basic set of data (96 samples), for all the new added samples I want the loop to be performed. First I want to determine the slope of the new dataset. This for loop was working perfektly when performed with performed with p=1. Afterwards, with line3 + Max3, I want to find out the localmax for the different p's. Line3 is calculated perfectly with 1:2 instead of p, when replaced it doesn't work. The error is: Index in position 1 exceeds array bounds. Index must not exceed 1.
I want to get sRay1l/sRay1r for all p's and afterwards the Ray1left to be calculated with this value.
new_samples = Xstart.nSample - base_samples;
for p = 1:new_samples
for k = 1:Xstart.nEm %slope
if (0 < k) && (k < Xstart.nEm)
dx3(p,k) = (Xstart.X(p,k+1,66) - Xstart.X(p,k,66)) / 2; %Bei Ex=447 nm
else
dx3(p,k) = 0;
end
end
line3 = Xstart.X(p,:,66);
Max3 = islocalmax(line3,2);
if Max3(p,64) == 1
sRay1l = 54+find(dx3(p,55:57)<0.01); %slopt left from localmax < 0.01 Abstand
if sRay1l > 0 %if there is sRay1l
Ray1left(p) = Xstart.Em(64) - Xstart.Em(max(sRay1l(p))); %lower boundary
else %otherwise distance = 0
Ray1left(p) = 0;
end
sRay1r = 64+find(dx3(p,65:71)>0); %slopt left from localmax > 0
if sRay1r > 0
Ray1right(p) = Xstart.Em(min(sRay1r(p))) - Xstart.Em(64); %above scatter
else
Ray1right(p) = 0;
end
else
Ray1left(p) = 0;
Ray1right(p) = 0;
end
end
Maybe someone is able to help.
Cheers,
Hanna
  2 Comments
Jan
Jan on 10 Aug 2022
Please post the complete error message. Then the readers do not have to guess, in which line the error occurs.
This part looks strange:
for k = 1:Xstart.nEm %slope
if (0 < k) && (k < Xstart.nEm)
dx3(p,k) = (Xstart.X(p,k+1,66) - Xstart.X(p,k,66)) / 2; %Bei Ex=447 nm
else
dx3(p,k) = 0;
end
end
In the loop over k=1:Xstart.nEM all k are > 0 and only the last k is not < Xstart.nEm. A simpler version:
dx3(p, Xstart.nEm) = 0;
dx3(p, 1:Xstart.nEm-1) = diff(Xstart.X(p, :, 66) / 2; %Bei Ex=447 nm
Jeffrey Clark
Jeffrey Clark on 10 Aug 2022
@Johanna Huber, you said line3 = Xstart.X(p,:,66) works when p=1:2 as would Max3 = islocalmax(line3,2) and following uses of it; in that case line3 is a matrix (1:2,:) and Max3 is a matrix. Now when p is a single value line3 and Max are only vectors (:) which will error out on statements like if Max3(p,64) == 1.

Sign in to comment.

Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!