1

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?

Wolfie
  • 27,562
  • 7
  • 28
  • 55
Maria
  • 157
  • 5
  • The first one is good, no need to change it. You can also always do `d=zeros(23,3)` and index each of the second dimension. – Ander Biguri Aug 15 '19 at 13:39

3 Answers3

5

Here is a compact way using deal :

[a, b, c] = deal(zeros(23,1));
rahnema1
  • 15,264
  • 3
  • 15
  • 27
3

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'} );     
Wolfie
  • 27,562
  • 7
  • 28
  • 55
3

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.

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
  • Structs aren't necessarily more efficient than tables... It depends what you're doing – Wolfie Aug 15 '19 at 20:14
  • @Wolfie: sure. But `A.field` is significantly faster if `A` is a struct than a table. A table is a user class, so indexing into it runs some M-file code. A struct is a built-in type. There's a Q&A somewhere on here where these two are timed. – Cris Luengo Aug 15 '19 at 20:25