How can i run 2 for loops at the same time?

15 次查看(过去 30 天)
My problem with the code below is that i can't run the two for loops at the same time.I want to check for j=1 and p=1 which of the if conditions is true and do the actions,then check for j=2 and p=4 etc.But the way it is right now , it will check for j=1 and for every p possible untill it changes for j=2.
Any help will be much appreciated
function z=coder(y,d)
ymin=min(y);
Number_samples=length(y);
z=zeros(1,Number_samples*3);
for j=1:Number_samples
for p=1:3:Number_samples*3-2
if y(j)==ymin
z(1,p)=0;
z(1,p+1)=0;
z(1,p+2)=0;
elseif y(j)==ymin+d
z(1,p)=0;
z(1,p+1)=0;
z(1,p+2)=1;
elseif y(j)==ymin+2*d
z(1,p)=0;
z(1,p+1)=1;
z(1,p+2)=0;
elseif y(j)==ymin+3*d
z(1,p)=0;
z(1,p+1)=1;
z(1,p+2)=1;
elseif y(j)==ymin+4*d
z(1,p)=1;
z(1,p+1)=0;
z(1,p+2)=0;
elseif y(j)==ymin+5*d
z(1,p)=1;
z(1,p+1)=0;
z(1,p+2)=1;
elseif y(j)==ymin+6*d
z(1,p)=1;
z(1,p+1)=1;
z(1,p+2)=0;
end
end
end
end
  3 个评论
Petros Mata
Petros Mata 2020-6-6
I want it to be:
(1,1)
(2,4)
(3,7)
(4,10)
etc.
If i use only one loop , lets say for j=1:Number_samples, i will have to change z(1,p) , z(1,p+1) , z(1,p+2) to z(1,j) , z(1,j+1) , z(1,j+2) for every if condition.Then for j=1 , i will see which if condition is true for y(1) and i will have a result to the z(1,1) , z(1,2) , z(1,3) , but then when j=2 i will put the next results to z(1,2) , z(1,3) , z(1,4) which two of them i already have. I used the two loops hoping that firstly it will check for j=1, which of the y(1) conditions is correct then for p=1 put z(1,1) , z(1,2) and z(1,3) and after that for j=2 , which of the y(2) conditions is correct then for p=4 put z(1,4),z(1,5),z(1,6) etc.
I hope what I'm trying to say is clear enough.
Image Analyst
Image Analyst 2020-6-6
When you say at the "same time" do you mean like in parallel, like with "parfor" in the Parallel Processing Toolbox?

请先登录,再进行评论。

回答(1 个)

the cyclist
the cyclist 2020-6-6
编辑:the cyclist 2020-6-6
From your reply to my comment, it seems to me that you really do only need one for loop. Instead of your
for j=1:Number_samples
for p=1:3:Number_samples*3-2
if y(j)==ymin
...
you instead just need
for j=1:Number_samples
p = j+3; % No for loop here. Just need p to be j+3 in each j-loop
if y(j)==ymin
...
That will give the (i,j) pattern
(1,1)
(2,4)
(3,7)
(4,10)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by