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

18 次查看(过去 30 天)
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.

采纳的回答

Rik
Rik 2018-6-23
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 个评论
Walter Roberson
Walter Roberson 2018-6-23
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

请先登录,再进行评论。

更多回答(1 个)

Igor Kubyshkin
Igor Kubyshkin 2020-4-17
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

类别

Help CenterFile Exchange 中查找有关 Elementary Math 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by