0

I'm trying to make a Matlab script to write output to a *.dat files from multiple matrices. Matrix "C" will go to C.dat e.t.c.

C = rand(10,3);
R = rand(12,3);
B = rand(15,3);
W_u = rand(20,3);
W_l = rand(20,3);

names = {'C', 'R', 'B', 'W_u', 'W_l'};
for i = 1:length(names);

Output = eval(names(i));    % <- Not working as I wanted.
                            % I need this to read matrix C when i=1 e.t.c.
                            % But when using eval('C') it works for the
                            % first one but the rest will obviously be wrong

filename = char(strcat(names(i), '.dat'));  % Creating output filename.
fid = fopen(filename, 'w');                 % Opening string.
fprintf(fid, '%d\t 1\n', size(Output,1));   % Opening and writing 'header' with matrix size
fprintf(fid, '%g\t%g\t %g \n', Output.' );  % Opening and writing data.
fclose(fid);                                % Closing the created file.
end

I need to define the Output as the Matrix C

Output = C   % C the Matrix.

NOT

Output = 'C' % Not C as a String.

But in the for loop I only have the C as a string

There is probably another ways doing this. I will also accept other methods if someone knows another easier method.

Bjartmar
  • 163
  • 13
  • 1
    How are you creating the multiple named variables in the first instance? You should avoid doing this at all costs - look into cell arrays or structs, instead. – nkjt Sep 17 '16 at 16:37
  • Please don't do this... – Suever Sep 17 '16 at 16:50
  • I figured this wasn't the best method... But I don't know how else I should do this? I can do this manually for each matrix. But I would like to have this in a loop. – Bjartmar Sep 17 '16 at 16:54
  • `things_to_process = {C, R, B, W_u, W_l}; for k = 1:numel(things_to_process); dothing(things_to_process{k}); end` – Suever Sep 17 '16 at 16:58
  • @Suever - Maybe this question is a duplication - But I have slight different problem than the other guy had. I can't use `eval(names(i))` but as I put in the description I can use `eval('C')`. Even though the `names(1)` is eqal to `'C'`. I saw that thread and picked the `eval' function from there. – Bjartmar Sep 17 '16 at 17:14
  • 1
    You need to use `{}` indexing since it's a cell array: `eval(names{i})`. Also you may need to do: `eval(['Output = ', names{i}, ';'])` – Suever Sep 17 '16 at 17:15

0 Answers0