Creating new variable in a subfunction .m file

1 回表示 (過去 30 日間)
Wei Nick Chan
Wei Nick Chan 2016 年 6 月 20 日
編集済み: per isakson 2016 年 6 月 20 日
Here's the case, I have one main matlab file (main.m) and another sub matlab file (sub.m)
And I need to loop over main.m multiple times to execute sub.m, is it possible to create a new array containing the output of the sub.m? Or I must have a global variable declared and include it in the function
Let this be the case:
First loop:
A=[1 2 3 4 5];
Second loop:
A=[2 8 5 9 6];
Nth loop:
A=[x x x x x];
I need to create an array in the subfunction so that it is able to recognize and store all the maximum of As in the loop
Max_A=
5
9
.
.
N

採用された回答

Shameer Parmar
Shameer Parmar 2016 年 6 月 20 日
file 1
function main()
% your code
for loop for calling the sub () for N number of time
% your code which calculating the following 1x5 array.
% A = [1 2 3 4 5] % this is just example
% now pass this array as input to sub () like
max{i} = sub(A).....% here you passing A array to sub() and it giving you max value which store into another array max.
end of for loop.
file 2
% following code for sub()
function output = sub(inputArray)
output = max(inputArray);
% end of function sub()
So in this way you are calling sub function for N number of time and all time it giving you max value which store into new aray Max, so at the end you will get all max values in variable Max.

その他の回答 (1 件)

per isakson
per isakson 2016 年 6 月 20 日
編集済み: per isakson 2016 年 6 月 20 日
No globals needed. Try
%%in main
R = nan( N, 5 ); % pre-allocate memory
for jj = 1 : N
R(jj,:) = sub();
end
I don't get the last part. Why not simply add after the loop
max_A = max( R, 2 );
  3 件のコメント
per isakson
per isakson 2016 年 6 月 20 日
編集済み: per isakson 2016 年 6 月 20 日
"instead of overwriting each other" &nbsp the code I proposed doesn't overwrite.
If the problem is that R outgrows the physical memory (RAM), then you need to store to a file.
per isakson
per isakson 2016 年 6 月 20 日
編集済み: per isakson 2016 年 6 月 20 日
  • "particular function" &nbsp I assume that's sub
  • Is max values from previous calls used in sub? If so, sub has state. You could use a persistent variable to keep previous max values. However, there must be a better way.

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

カテゴリ

Help Center および File ExchangeWorkspace Variables and MAT-Files についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by