storing tables in an array and calling them whithin a for loop

5 views (last 30 days)
I am a novice in MatLab. I have 30 different tables that imported in Matlab as CSV files. I want to choose two pairs of the tables and read a column Return of them and store it in ret_1 and ret_2 variables. Something like the following code:
data = {'AAPL', 'AXP', 'BBN'};
for i = length(data)
for j = length(data)
ret_1 = data(i).Return;
ret_2 = data(j).Return;
end
end
But I get an error, as data(i) doesn't include the content that I want to. I tried
eval(data(i)) but it says that eval() works only with strings and not arrays.
My data looks like the following in CSV files that I imported them into MatLab.
'AAPL' =
Date Low Close Return
6/3/1997 16.750 16.935 16.687
6/4/1997 16.625 16.756 16.625
6/5/1997 16.625 17.125 16.687
'AXP' =
Date Low Close Return
6/3/1997 69.079 70.075 68.750
6/4/1997 69.079 69.079 68.500
6/5/1997 68.078 69.876 67.750

Accepted Answer

Peter Perkins
Peter Perkins on 1 Sep 2017
You've shown your data, but that can't possibly be output from MATLAB because
'AAPL' =
is not something MATLAB would ever display. I'm gonna assume you've done something like
aapl = readtable('aapl.csv');
axp = readtable('axp.csv');
...
It's almost never a good idea to try to do this via an eval. A reasonable thing to do might be to use a scalar struct with fields named 'aapl', etc. So
data.aapl = readtable('aapl.csv');
data.axp = readtable('axp.csv');
and then
fn = fieldnames(data);
for i = 1:length(fn)
for j = 1:length(fn)
ret_1 = data.(fn{i}).Return;
ret_2 = data.(fn{j}).Return;
end
end

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!