フィルターのクリア

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

22 ビュー (過去 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 Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by