Strange outputs when using disp or fprintf

4 visualizaciones (últimos 30 días)
Alexander Babayi
Alexander Babayi el 3 de Oct. de 2016
Comentada: Stephen23 el 3 de Oct. de 2016
I currently have a code with which you input 2 numbers (x and y) and two outputs should come up (th and r). I'm having some trouble getting matlab to actually display those two outputs in the command window. Although the correct values for those outputs are listed in the workspace, my code doesn't seem to be able to reproduce those two outputs. Here is the code:
prompt = 'Enter x value';
x = input(prompt)
prompt = 'Enter y value';
y = input(prompt)
r = sqrt(x.^2 + y.^2);
if x>0;
t = atan(y/x);
elseif x<0, y>0;
t = atan(y/x)+pi;
elseif x<0, y<0;
t = atan(y/x)-pi;
elseif x<0, y==0;
t = pi;
elseif x==0, y>0;
t = pi/2;
elseif x==0, y<0;
t = -pi/2;
elseif x==0, y==0;
t = 0;
end
th = rad2deg(t);
fprintf('r = %s', r);
fprintf('theta = %s degrees', th);
The "r" output value displayed in the command window, for some reason, gives me a box symbol. The "th" output value displayed in the command window gives me a "Z". I'm not sure how it is displaying these outputs, as the correct ones are in the workspace. Maybe the part of the code that is meant to print them in the command box is faulty?
Thank you.
  2 comentarios
Steven Lord
Steven Lord el 3 de Oct. de 2016
In addition to what Walter said, this line of code won't do what you want.
elseif x<0, y>0;
To combine multiple conditions in an if statement you need to combine them with and or or.
Alexander Babayi
Alexander Babayi el 3 de Oct. de 2016
Thank you, I was actually just testing it and wondering why it wasn't working the way I intended. I used "&&" to combine the two conditions, if that also works. It seems to have worked.

Iniciar sesión para comentar.

Respuesta aceptada

Walter Roberson
Walter Roberson el 3 de Oct. de 2016
Don't use %s for numeric values. %s is for strings. Use %f or %e or %g for numeric values.
  2 comentarios
Alexander Babayi
Alexander Babayi el 3 de Oct. de 2016
Thank you, I didn't realize that.
Stephen23
Stephen23 el 3 de Oct. de 2016
@Alexander Babayi: you don't need to guess how MATLAB works (e.g. what fprintf format string to use), you could try reading the documentation:

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by