Help with if statement in a calculation loop
Mostra commenti meno recenti
Hello,
I have a problem with a code. I want to calculate some numbers but I want to "limit" my results via a loop.
I want values <1 to be =1, values with >10 to be 10 and the others to be calculated from this equation:
x= x*1.3+0.5. I wrote this code but it is not use
x= 5 + randn * 0.5
if x < 1
x == 1
elseif x > 10
x == 10
else x > 3
x == 1.3* x -0.75
end
Where is the problem?
Thanking you in advance
2 Commenti
Nino Wyssen
il 12 Apr 2021
I can see several problems here.
First, Matlab likes the lines to be finished with a semicolon, but this isn't necessary if you don't mind your programm outputting all the operations.
Then, you aren't assigning values. You are comparing them. To assign a new value to a variable you only need one equal sign.
Third, you can't use a condition for you else statment, if you only wnt to execute the command below u need to use another elseif.
From your description I suspect the following code does the right thing for you:
x= 5 + randn * 0.5;
if x < 1
x = 1;
elseif x > 10
x = 10;
else
x = 1.3* x -0.75;
end
even though I think it would be better to use a new variable for your result
x= 5 + randn * 0.5;
if x < 1
y = 1;
elseif x > 10
y = 10;
else
y = 1.3* x -0.75;
end
Ivan Mich
il 12 Apr 2021
Risposta accettata
Più risposte (1)
The problem is that you assume Matlab will process each element of x separately. Matlab will only do that if you use a loop.
An alternative is to use logical indexing to process x as an array.
L=x<1;
x(L)=1;
L=x>10;
x(L)=10;
L=x>3;
x(L)=1.3* x(L) -0.75;
4 Commenti
Ivan Mich
il 12 Apr 2021
Rik
il 12 Apr 2021
Can you spot why it doesn't work? Can you also see how you could fix it?
The simplest solution would be to create a second array:
L=x<1;
y(L)=1;
L=x>10;
y(L)=10;
L=x>3 & x<10;
y(L)=1.3* x(L) -0.75;
Ivan Mich
il 12 Apr 2021
Rik
il 12 Apr 2021
In that case you should use the code Stephen suggested.
If you have a piecewise function you can use the code I suggested.
Categorie
Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!