Function output into a variable

11 visualizaciones (últimos 30 días)
Synthia Caruvana
Synthia Caruvana el 20 de Mzo. de 2019
Comentada: dpb el 30 de Abr. de 2019
How do I insert my function outputs into a variable in my script?
Here's my function:
function [r,th] = AddVecPol(r1,th1,r2,th2)
% Getting values of x and y within each vector
x1 = r1*cosd(th1);
y1 = r1*sind(th1);
x2 = r2*cosd(th2);
y2 = r2*cosd(th2);
% Adding the x and y components of each vector together
x = x1+x2;
y = y1+y2;
% Calculating the radius and angle of the added vectors
r = sqrt(x^2 + y^2)
th_rad = atan(y/x);
th = rad2deg(th_rad)
end
And here is my script that I'm calling it to:
AddVecPol(5,23,12,40);
% Generating the output
fprintf(1,'Egr 109 Homework 5 Problem 6\n')
fprintf(1,' \n')
fprintf(1,'Part a\n')
fprintf(1,'r1 = ( 5.0 <23.0o)\n')
fprintf(1,'r2 = (12.0 <40.0o)\n')
fprintf(1,'resultant = ( %3.3 <%3.3o)\n', [r,th])
I've left r and th in the function without a semicolon at the end so that I can see that I am getting the right answers in the command window, and I am, but I can't put them into the last line of my output (last fprintf line) because r and th are not showing up as variables in my workspace. How can I make them become variables in my script? Thanks!

Respuestas (2)

dpb
dpb el 20 de Mzo. de 2019
[r th]=AddVecPol(5,23,12,40);
ML only returns results if you provide somewhere for it to throw them...otherwise the first of multiple results goes into the default ans variable, but anything else is just tossed in the bit bucket...
  3 comentarios
Steven Lord
Steven Lord el 20 de Mzo. de 2019
See this documentation page for an example of how to return outputs from a function.
dpb
dpb el 20 de Mzo. de 2019
That's what the line above does...

Iniciar sesión para comentar.


Ryan Hirsch
Ryan Hirsch el 30 de Abr. de 2019
I think it should be this but I am not positive.
y2 = r2*sind(th2);
  1 comentario
dpb
dpb el 30 de Abr. de 2019
Good catch on the actual internals to the function while we were all focused on the retrurned value syntax, ignoring the results...

Iniciar sesión para comentar.

Categorías

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