# How to check if several variables exist and assign a value to non-existing variables?

54 views (last 30 days)
Carlos HM on 23 Jun 2018
Commented: Stephen on 18 Apr 2020
I am trying to check if several variables exist, and assign a value to those of them who do not exist.
a=7;
e=4;
nums=["a", "b", "c", "d", "e", "f"];
i=1;
while i<=length(nums)
if exist(nums(i),'var')==0
eval(nums(i))=i;
end
i=i+1;
end
b, c, d and f do not exist before the while loop, so they should get assigned a value. But it doesn't work, I get the following error:
Function 'subsindex' is not defined for values of class 'string'.
Stephen on 23 Jun 2018

Rik on 23 Jun 2018
Replacing bij chars arrays makes it work, although I wonder about eval. It's generally a bad idea, but I don't see a good alternative without knowing the context that you plan to use this in.
a=7;
e=4;
nums=['a', 'b', 'c', 'd', 'e', 'f'];
i=1;
while i<=length(nums)
if exist(nums(i),'var')==0
eval([nums(i) '=i;'])
end
i=i+1;
end
Walter Roberson on 23 Jun 2018
a=7;
e=4;
nums={'a', 'b', 'c', 'd', 'e', 'f'};
i=1;
while i<=length(nums)
if exist(nums{i},'var')==0
eval([nums{i} '=i;'])
end
i=i+1;
end
or
a=7;
e=4;
nums=["a", "b", "c", "d", "e", "f"];
i=1;
while i<=length(nums)
if exist(nums(i),'var')==0
eval([nums(i) + '=' + i]);
end
i=i+1;
end

Igor Kubyshkin on 17 Apr 2020
more simple
a=7;
e=4;
nums='abcdefg';
i=1;
while i<=length(nums)
if exist(nums(i),'var')==0
eval([nums(i), '=i']);
end
i=i+1;
end
Stephen on 18 Apr 2020
Even simpler: use one vector.