problem with sum in function

1 次查看(过去 30 天)
Hello every one!
I am new with matlab and i have a problem with very simple program with matlab 2019a
Code 1:
clear all;
z=so;
function [s] = so
A=[1 5 3 4 2 10 21 65];
s = sum(A);
s = s+1;
end
The answer is z=112, it's correct
Code 2:
clear all;
A=[1 5 3 4 2 10 21 65];
z=so;
function [s] = so
s = sum(A);
s = s+1;
end
I get this error
So as far as i understand, "Sum" can not read the variable out of the function "so".
DId i do somethings wrong or my computer have issues?
It's just a little test, but i need to get work with "sum" in a function so I can write a bigger program.

采纳的回答

Steven Lord
Steven Lord 2020-4-22
That is correct. Functions operate in their own workspaces.
Variables from outside the function generally only enter a function's workspace when passed as input arguments to the function.
Variables from inside the function generally only leave the function's workspace to enter a different workspace when returned from the function as an output argument.
Functions generally can't access variables outside their own workspace.
[Those rules aren't technically complete, but when you're starting out they're a good mental model to use as a starting point for your MATLAB knowledge.]
In your first example you created the variable A inside so's workspace so the so function has access to the A variable. Since you didn't return A from so, A is not added to the workspace from which so was called when the so function returns.
In your second example you created A outside so's workspace and didn't pass it in as an input, so the so function doesn't have access to the A variable.

更多回答(1 个)

Fangjun Jiang
Fangjun Jiang 2020-4-22
You are right. All you need to do is "function [s] = so(A)" to pass in the value of A.
  2 个评论
ronaldo messi
ronaldo messi 2020-4-22
how fool i am. Thank you so much Fangjun Jiang!
Steven Lord
Steven Lord 2020-4-22
You're not a fool. You said you're new with MATLAB, and that means there are things you don't know. That's how everyone, with the possible exception of Cleve, started out. And Cleve is a bit of a special case, being the author of the first version of MATLAB.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by