Borrar filtros
Borrar filtros

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

15 visualizaciones (últimos 30 días)
Mizo Amreya
Mizo Amreya el 15 de Jul. de 2020
Respondida: Cris LaPierre el 15 de Jul. de 2020
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

Respuestas (1)

Cris LaPierre
Cris LaPierre el 15 de Jul. de 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

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by