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

36 visualizzazioni (ultimi 30 giorni)
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'.
Thank you for your help.

Risposta accettata

Rik
Rik il 23 Giu 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
  1 Commento
Walter Roberson
Walter Roberson il 23 Giu 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

Accedi per commentare.

Più risposte (1)

Igor Kubyshkin
Igor Kubyshkin il 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

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by