How to make a while loop fill out an array?

3 ビュー (過去 30 日間)
Chris Heard
Chris Heard 2019 年 1 月 5 日
コメント済み: dpb 2019 年 1 月 6 日
Hello, I am trying to use a while loop to move through an array of strings and allocate the strings to a corresponding number system. Tstr provides the string array for the switch input. The output should be 1 1 7 1 2 1 4 1 3 complementing 'DEB' 'DEB' 'TFR' 'DEB' 'DD' 'DEB' 'FPI' 'DEB' 'CPT' however it returns 1 8 8 8 8 8 8 8 8. Please help me to return the intended array.
Tlist = { 'DEB' 'DEB' 'TFR' 'DEB' 'DD' 'DEB' 'FPI' 'DEB' 'CPT'};
l = length(Tlist);
n=1;
while n <= l
Tstr(1,n) = string(Tlist(1,n));
switch Tstr
case 'DEB'
Tt(1,n) = 1;
case 'DD'
Tt(1,n) = 2;
case 'CPT'
Tt(1,n) = 3;
case 'FPI'
Tt(1,n) = 4;
case 'FPO'
Tt(1,n) = 5;
case 'CHG'
Tt(1,n) = 6;
case 'TFR'
Tt(1,n) = 7;
otherwise
Tt(1,n) = 8;
end
n=n+1;
end
  1 件のコメント
dpb
dpb 2019 年 1 月 5 日
HINT:
What happens to
Tstr(1,n) = string(Tlist(1,n));
when n > 1 later on when you use simply Tstr?

サインインしてコメントする。

採用された回答

dpb
dpb 2019 年 1 月 5 日
編集済み: dpb 2019 年 1 月 5 日
Tlist = { 'DEB' 'DEB' 'TFR' 'DEB' 'DD' 'DEB' 'FPI' 'DEB' 'CPT'};
lup={'DEB','DD','CPT','FPI','FPO','CHG','TFR'};
>> [~,Tt]=ismember(Tlist,lup)
Tt =
1 1 7 1 2 1 4 1 3
>>
for fixup for missing elements add
Tt(Tt==0)=numel(lup)+1;
  2 件のコメント
Chris Heard
Chris Heard 2019 年 1 月 6 日
編集済み: Chris Heard 2019 年 1 月 6 日
Thanks a lot. Don't fully understand why the loop didn't work still but at least I can crack on with it now.
EDIT. Got it, need to switch on Tstr(1,n).
dpb
dpb 2019 年 1 月 6 日
Right, that would work. While the vectorized solution is probably the way to go, the loop/switch construct variable doesn't need the subscript at all...
Tstr=string(Tlist(1,n));
switch Tstr
...
Or, you could even eliminate the temporary entirely.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeParallel for-Loops (parfor) についてさらに検索

タグ

製品


リリース

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by