Effacer les filtres
Effacer les filtres

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

22 vues (au cours des 30 derniers jours)
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.

Réponse acceptée

Rik
Rik le 23 Juin 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 commentaire
Walter Roberson
Walter Roberson le 23 Juin 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

Connectez-vous pour commenter.

Plus de réponses (1)

Igor Kubyshkin
Igor Kubyshkin le 17 Avr 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

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by