Create vector/matrix inside function

2 ビュー (過去 30 日間)
Tejay Lovelock
Tejay Lovelock 2016 年 5 月 9 日
コメント済み: Stefan Raab 2016 年 5 月 9 日
Hi All,
I have a simple function file.
If I put something like this inside the function file; A = [1 2 3 4];
It will display this in the command window;
A = 1 2 3 4
But it won't save A in the Workspace as a vector.
How can I create a vector inside a function file and have that vector saved to my Workspace?
Thanks!

採用された回答

Stephen23
Stephen23 2016 年 5 月 9 日
編集済み: Stephen23 2016 年 5 月 9 日
You return it as an output argument.
Like the MATLAB documentation clearly states, the best practice is to pass arguments:
So your function could be something like:
function [ct,A] = critPT( ... )
...
A = ...
ct = ...
...
end
and then call it:
[NewCT,newA] = critPT(...)
Note: the fact that you do not "see" the variable A in the base workspace is the whole point of functions: they should have independent workspaces, so that what happens inside any one function does not affect any other workspace. That is the point.
  1 件のコメント
Tejay Lovelock
Tejay Lovelock 2016 年 5 月 9 日
Thanks for that!

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

その他の回答 (1 件)

Stefan Raab
Stefan Raab 2016 年 5 月 9 日
Hello,
this is because functions have their own workspace. There is a good explanation in the MATLAB doc, please execute the following commands in the MATLAB Command Window to open the help browser:
  • Information on workspaces in general:
web(fullfile(docroot, 'matlab/matlab_prog/base-and-function-workspaces.html'))
  • Information on how to share data between workspaces:
web(fullfile(docroot, 'matlab/matlab_prog/share-data-between-workspaces.html'))
I hope this will help you.
Kind regards, Stefan
  2 件のコメント
Tejay Lovelock
Tejay Lovelock 2016 年 5 月 9 日
Thanks Stefan
Stefan Raab
Stefan Raab 2016 年 5 月 9 日
Ah, I was too slow :)

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

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by