Maria
Maria

Reputation: 157

How to create idendical variables in MATLAB from an array of variable names?

I have the following code in Matlab:

a = zeros(23,1)
b = zeros(23,1)
c = zeros(23,1)

How can I write it more compactly? I was looking for a solution that is something like this:

str = {'a','b','c'}
for i = str{i}
    i = zeros(23,1)
end

But I can't find a way to do it properly without an error message. Can someone help please?

Upvotes: 1

Views: 84

Answers (3)

Cris Luengo
Cris Luengo

Reputation: 60494

You can also use a struct if the variable name is important:

str = {'a','b','c'};
data = struct
for ii = 1:numel(str)
    data.(str{ii}) = zeros(23,1);
end

The struct is more efficient than the table. You can now address data.a, data.b, etc.

But if the name is not useful, it's best to put your data into a cell array:

N = 3;
data = cell(N,1);
for ii = 1:N
    data{ii} = zeros(23,1);
end

or simply:

data = cell(3,1);
[data{:}] = deal(zeros(23,1));

Now you address your arrays as data{1}, data{2}, etc., and they're always easy to address in loops.

Upvotes: 3

Wolfie
Wolfie

Reputation: 30047

What you're tempted to do is very bad practise, but can be done like this

str = {'a','b','c'};
for ii = 1:numel(str)
    eval( [str{ii} ' = zeros(23,1)'] );
end

Why is this bad practise?

  • Your code legibility has just gone way down, you can't clearly see where variables are declared.
  • eval should be avoided

You could use deal to make things a bit nicer, but this doesn't use the array of variable names

[a, b, c] = deal( zeros(23, 1) );

Even better, it's likely you can optimise your code by using a matrix or table instead of separate 1D arrays. The table option means you can still use your variable name array, but you're not using eval for anything!

% Matrix
M = zeros( 23, 3 ); % Index each column as a/b/c using M(:,1) etc

% Table, index using T.a, T.b, T.c
T = array2table( zeros(23,3), 'VariableNames', {'a','b','c'} );     

Upvotes: 3

rahnema1
rahnema1

Reputation: 15837

Here is a compact way using deal :

[a, b, c] = deal(zeros(23,1));

Upvotes: 5

Related Questions