How do I change the increment in an if statement inside a loop
15 次查看(过去 30 天)
显示 更早的评论
Hi, I tried googling the previous questions but didn't find a similiar situation.
I've got an if statement inside a loop. I'm trying to establish conditions for my boundaries.
I'm having issues establishing conditions for the right & left boundaries.
I've kept my code simple since my concern is the "if conditions". I've attached a photo to make it clearer.
I guess I'm confused on the difference between = and ==.
I'm trying to make the counter jump from 1,16,31,46,etc.
according to Matlab documentation it should be i = 1:Imax:Imax*Jmax.
But when I use this I get an error Incorrect use of '=' operator. To assign a value to a variable, use '='. To compare values for equality, use
'=='.
Please advise. Thanking you in advance.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/332105/image.jpeg)
Imax = 15;
Jmax = 15;
for i=1:Imax*Jmax % Lower Boudary (It works)
if i <= Imax
C(i) = 0;
else
C(i) = 1;
end
if i = 1:Imax:Imax*Jmax % Left Boundary (Doesn't work)
D(i) = 0;
else
D(i) = 1;
end
if i = Imax:Imax:Imax*Jmax % Right Boudary (Doesn't work)
F(i) = 0;
else
F(i) = 1;
end
if i > (Imax*Jmax)-Imax % Upper Boundary (It works)
G(i) = 0;
else
G(i) = 1;
end
end
回答(1 个)
Cris LaPierre
2020-7-15
I guess I'm confused on the difference between = and ==.
One equals means 'set equal to or assign'. x=5 assign x a value of 5.
Two equals is for comparing two values for equality. x==5 checks if the value of x is 5. If it is, the output is 1, otherwise it is 0.
How do I change the increment in an if statement inside a loop
If statements do not loop. They execute based on the result of a conditional statement. That condition must return a single logical value. Typically, these conditional statements use <,<=,==,>=, or >, but never =. Place this inside a loop (for/while) to check multiple conditions, where each loop checks a single condition.
if ismember(i,1:Imax:Imax*Jmax)
...
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!