How to save variables in a function to the workspace

i want to save the variables( x , y , z , xx , yy) in a function to the workspace.
**************************************
global x
global y
global z
global xx
global yy
test(1,2,3)
function test(x,y,z)
x
y
z
x+y+z
test2(4,2)
end
function test2(xx,yy)
xx
yy
xx-yy
end

 Accepted Answer

Don't use globals. Return your variables through the function output. See the documentation. This example from that page shows how to return the variable ave.
myave = average([1:10])
myave = 5.5000
% function declaration
function ave = average(x)
ave = sum(x(:))/numel(x);
end

9 Comments

thank you for reply.
i want to try get the variables( 'i ')
my except value is i = 11;
after getting the the variables( 'i ')
use for other calculation.
function ()
function ()
for i=1:10
i = i+1;
end
end
end
Not enough details to provide a solution I like. Can you also show where you want to use i?
When you modify a for loop variable, your for i and i=i+1 then each time the for starts a new iteration, it will discard the previous changes. At the end, it will be left with the last value assigned to the loop variable. So all the iterations i=1:10 happen as-if you were not modifying i, but when i=10 your i=i+1 does have effect leaving you with 11 as the final value.
I will attach the script file which base file is sample file in mathworks .
i modifid for getting the coordinate.
i wanna to get ax(i), ay(i) vaule .
Change
function MotionBasedMultiObjectTrackingExample()
to
function [ax, ay] = MotionBasedMultiObjectTrackingExample()
Not enough i didn't get the ax,ay
i tried the sinple script, but ans = 1;
test(1,2,3)
function [x,y,z] = test(x,y,z)
x+y+z
end
and also, it occuer the below error.
how to avoid this error?
The index at position 1 exceeds the array range (must not exceed 2).
error: MotionBasedMultiObjectTrackingExample (line 80)
bx=centroids(k,1);
ans = 1 for that function because you did not assign the outputs to variables. When you have multiple outputs and do not assign to variables, then the result of the expression is considered to be the first output.
@Hiroyasu Fujita: how to call functions with one or more outputs is explained here:
Those tutorials explain many basic concepts that you will need to know if you want to use MATLAB.
@Stephen Cobeldick , @Walter Roberson @Cris LaPierre
Thank you for your comments.
The problem has been solved.

Sign in to comment.

More Answers (0)

Categories

Tags

Community Treasure Hunt

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

Start Hunting!