Access and write data variables from function in using function?
4 次查看(过去 30 天)
显示 更早的评论
Greetings.
I have 2 matlab files.
- resample.m
- 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
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
2021-2-10
编辑:Jan
2021-2-10
Please read this carefully:
- https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval
- https://www.mathworks.com/matlabcentral/answers/57445-faq-how-can-i-create-variables-a1-a2-a10-in-a-loop
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!