Function output into a variable

18 Ansichten (letzte 30 Tage)
Synthia Caruvana
Synthia Caruvana am 20 Mär. 2019
Kommentiert: dpb am 30 Apr. 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!

Antworten (2)

dpb
dpb am 20 Mär. 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 Kommentare
Steven Lord
Steven Lord am 20 Mär. 2019
See this documentation page for an example of how to return outputs from a function.
dpb
dpb am 20 Mär. 2019
That's what the line above does...

Melden Sie sich an, um zu kommentieren.


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

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Function Creation finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by