mathstackuser123
mathstackuser123

Reputation: 305

MATLAB - the function returns unwanted output

and I am pretty new at it. I wrote the simple function below, which gets a pair and returns the polar form

function [r,a] = rect2polar(x,y)
    r = sqrt(x^2 + y^2);
    a = atan(y/x);
    [r,a]
end

and when I try for example rect2polar(3,5) it gives me the next output:

ans =
5.8310    1.0304

ans =
5.8310 

It returns the desired output, plus the output 5.8310, in other words it returns the variable r in the function for the second time. How can I fix this? Writing

rect2polar(3,5);

helped (the difference is that I wrote ; at the end), but it doesn't feel right. Any help is appreciated, thanks!

Upvotes: 0

Views: 73

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112659

The first displayed part,

ans =
   5.8310 1.0304

is produced by this line in your function

[r,a]

Since it is missing a ;, Matlab displays the result.

The second part,

ans =
   5.8310

is produced because when you call the function as rect2polar(3,5) you are indicating that you want only one output, namely the first, which is displayed after the function returns.

So, the solution would be:

  • Remove the line [r, a] in your function, which is doing nothing but display what the function will output;
  • Call your function as [out1, out2] = rect2polar(3,5).

Or, if you want the function to return a vector:

function out = rect2polar(x,y)
    r = sqrt(x^2 + y^2);
    a = atan(y/x);
    out = [r,a];
end

Upvotes: 4

Related Questions