How do I change the increment in an if statement inside a loop

23 views (last 30 days)
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.
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

Answers (1)

Cris LaPierre
Cris LaPierre on 15 Jul 2020
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 you want to check if your variable is one of multple possibilities, use the ismember function.
if ismember(i,1:Imax:Imax*Jmax)
...
end

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!