Borrar filtros
Borrar filtros

If statement with 2 commands

1 visualización (últimos 30 días)
Jay
Jay el 29 de Abr. de 2016
Comentada: Stephen23 el 29 de Abr. de 2016
I have a 1 x 3 matrix (DMS).
Values are [26, 50, 60]
Code is:
if DMS(1,3) == 60
DMS (1,2) = DMS (1,2) + 1 & DMS(1,3) == 0
else
end
The purpose is to roll over (add 1) to the second elements value and set the third elements value to 0.
During runtime I am getting a value of [26, 0, 60].
What is wrong with my coding of the if statement for the desired values to be returned?

Respuesta aceptada

Roger Stafford
Roger Stafford el 29 de Abr. de 2016
Editada: Roger Stafford el 29 de Abr. de 2016
Your code should be:
if DMS(1,3) == 60
DMS (1,2) = DMS (1,2) + 1;
DMS(1,3) = 0;
end
The '&' operator is not to be used as "do this AND do this". It functions only as a logical operator such as (x<10)&(x>3) meaning that it is true if x is less than ten and greater than 3.
Also the '==' is not an assignment symbol. It is another logical operator. The expression x==5 is true whenever x is exactly equal to 5.
  1 comentario
Stephen23
Stephen23 el 29 de Abr. de 2016
Justin's "Answer" moved here:
Thanks Roger,
I should also use = and not == for 0 value.
That was fast and easy.
Thanks again.

Iniciar sesión para comentar.

Más respuestas (1)

Elias Gule
Elias Gule el 29 de Abr. de 2016
Ok, I think I see two problems in your if statement. 1). == is not an assignment operation, but rather a comparative one. So
DMS(1,3) == 0
checks if the value at row 1 column 3 of the DMS vector/matrix is 0; in your case it checks whether 60 is equal to 0, which returns 0 (a logical false is Matlab). 2). The & operator is a logical and. So
DMS (1,2) = DMS (1,2) + 1 & DMS(1,3) == 0
first calculates the value of DMS(1,2) + 1 => 51, then performs the operation described in 1) above, resulting 51 & 0, which returns 0.
To solve your problem: replace the ampersand ("&") with a semicolon (";"), and the "==" with "=", such that the statement will now be,
DMS (1,2) = DMS (1,2) + 1; DMS(1,3) = 0;

Categorías

Más información sobre Mathematics 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