Access and write data variables from function in using function?
3 views (last 30 days)
Show older comments
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 Comment
Stephen23
on 11 Feb 2021
"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).
Answers (1)
Jan
on 10 Feb 2021
Edited: Jan
on 10 Feb 2021
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 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!