Access and write data variables from function in using function?

조회 수: 4 (최근 30일)
SrinivasaRao Tanniru
SrinivasaRao Tanniru 2021년 2월 10일
댓글: Stephen23 2021년 2월 11일
Greetings.
I have 2 matlab files.
  1. resample.m
  2. writingfiles.m
in resample.m matlab file, there is a for loop, which I am using for storing data into 20 different matrices.
eg.
%d_time is the variable where I specify, a string representing data time,
% which I am planning to append before each file I am going to write at a later stage
d_time = DAY;
for f = 1:length(fileslist)
out1(:,f) = subfile_1 - subfile_2;
out2(:,f) = subfile_1 - subfile_3;
out3(:,f) = sufile_2 - subfile_3;
...
% multiple such outputs are there in the code
out30(:,f) = sufile_15 - subfile_13;
end
writingfiles(d_time)
The function code (writingfiles) for writing data into csv files is present in another matlab file.
The example code is as follows.
function x = writingfiles(d_time)
sArray = ["out1","out2","out3","out30"];
for s = 1 : length(sArray)
x = genvarname(sArray(s));
writematrix(eval(sArray(s)),s_time+"_"+sArray(s)+'.csv')
end
How ever, the above code is generating empty csv files (only name of the output file is stored in the csv else), However each csv file in my actual code should consist of about 14000 values.
I am new to matlab, I have tried help and used various functions such as eval, whos.name etc with not much luck.
Any help to move further, in this regard is highly valuable.
Thankyou.
  댓글 수: 1
Stephen23
Stephen23 2021년 2월 11일
"I am new to matlab, I have tried help and used various functions such as eval, whos.name etc with not much luck."
Numbering variables like that is a sign that you are doing something wrong.
The simple and efficient approach is to use indexing into one array (which could be a container array, e.g. cell array).

댓글을 달려면 로그인하십시오.

답변 (1개)

Jan
Jan 2021년 2월 10일
편집: Jan 2021년 2월 10일
Please read this carefully:
Avoid eval and hiding indices in the names of variables. This concerns "subfile_1" and "out1" etc.
Each Matlab function has its own worksapce. You cannot access the variables of workspaces of other functions. If you need the value, provide them by inputs and outputs.
genvarname produces a string or CHAR vector only. This does not magically allow to access the values of the variables having the same name in another function.
Use cell arrays to collect the variables: out{1} instead of out1, subfile{1} instead of subfile_1. Then processing the data in loop is easy.
Forward the variables you want to export as input arguments to your function writingfiles. Then you can access them for the output.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by