How to access variables from another function?

I want to accesses a variable in one function in another function. Here's part of the code:
function initial(hObject, eventdata, handles, varargin)
nproduto = randi([1,5],1,1)
end
function calcular(hObject, eventdata, handles)
set(handles.preco, 'String', nproduto)
end
It gives an error that doesn't recognize produto in the last function.

回答 (2 件)

Star Strider
Star Strider 2017 年 11 月 24 日

1 投票

Return the variables-of-interest as outputs:
function nproduto = initial(hObject, eventdata, handles, varargin)
nproduto = randi([1,5],1,1)
end
function calcular(hObject, eventdata, handles, nproduto)
set(handles.preco, 'String', nproduto)
end
You will need to call the ‘initial’ function somewhere in your code or in the ‘calcular’ function to put ‘nproduto’ in the ‘calcular’ function’s workspace.
Please do not use global variables to share data between workspaces!
I leave you otherwise to decide how best to transmit them between your functions and workspaces.

4 件のコメント

Renato Pereira
Renato Pereira 2017 年 11 月 25 日
Hey Star Strider, I add produto as variable on function calcular as you said but now when call it "Not enough input arguments." error appears. Think you can help?
Star Strider
Star Strider 2017 年 11 月 25 日
I hope so.
Note that in your ‘initial’ function, I added ‘nproduto’ as an output argument in the function declaration. You then have to call it first, before you call ‘calcular’:
nproduto = initial(hObject, eventdata, handles, varargin);
calcular(hObject, eventdata, handles, nproduto);
Renato Pereira
Renato Pereira 2017 年 11 月 25 日
I really thank you for your time!
I did exactly what you said. No idea why it keeps appearing the same error...
Star Strider
Star Strider 2017 年 11 月 25 日
My pleasure.
I cannot run your code. However I can simulate the problem.
When I run this test code:
f = @(x,y,varargin) (x+y).^2;
x = 1;
z = f(x);
it throws the error:
Not enough input arguments.
So you first need to be sure that you are passing all the necessary arguments to your function.

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeFoundation and Custom Domains についてさらに検索

質問済み:

2017 年 11 月 24 日

コメント済み:

2017 年 11 月 25 日

Community Treasure Hunt

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

Start Hunting!

Translated by