assign a value to a string

19 ビュー (過去 30 日間)
Saad
Saad 2012 年 12 月 14 日
Dear all,
I have a list of string:
txt={'BBB3', 'BBB2', 'BBB1', 'A3', 'A2', 'A1','AA3','AA2','AA1'};
i would like to assign a value to each string. For instance,
Here is my code for i=1:length(txt) if isequal(txt{'i'},'BBB3')
txt{'i'}=11;
elseif isequal(txt{'i'},'BBB2')
txt{'i'}=12;
elseif isequal(txt{'i'},'BBB1')
txt{'i'}=13;
elseif isequal(txt{'i'},'A3')
txt{'i'}=14;
elseif isequal(txt{'i'},'A2')
txt{'i'}=15;
elseif isequal(txt{'i'},'A1')
txt{'i'}=16;
elseif isequal(txt{'i'},'AA3')
txt{'i'}=17;
elseif isequal(txt{'i'},'AA2')
txt{'i'}=18;
else
txt{'i'}=20;
end
end
Basically the output I am looking for is:
txt={11, 12, 13, 14, 15, 16, 17, 18 ,19};
however when I run the code and type txt in the screen in order to retrieve the final output i still get the initial input which is txt={'BBB3', 'BBB2', 'BBB1', 'A3', 'A2', 'A1','AA3','AA2','AA1'};
I might have missed something somewhere. ANy help is much appreciated Thanks

採用された回答

Image Analyst
Image Analyst 2012 年 12 月 14 日
Try it without the apostrophes around the i:
txt={'BBB3', 'BBB2', 'BBB1', 'A3', 'A2', 'A1','AA3','AA2','AA1'};
for k =1 : length(txt)
if isequal(txt{k},'BBB3')
txt{k}=11;
elseif isequal(txt{k},'BBB2')
txt{k}=12;
elseif isequal(txt{k},'BBB1')
txt{k}=13;
elseif isequal(txt{k},'A3')
txt{k}=14;
elseif isequal(txt{k},'A2')
txt{k}=15;
elseif isequal(txt{k},'A1')
txt{k}=16;
elseif isequal(txt{k},'AA3')
txt{k}=17;
elseif isequal(txt{k},'AA2')
txt{k}=18;
else
txt{k}=20;
end
end
celldisp(txt);
  1 件のコメント
Saad
Saad 2012 年 12 月 14 日
Thanks a lot it is working now...thank you for your help

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

その他の回答 (1 件)

Wayne King
Wayne King 2012 年 12 月 14 日
編集済み: Wayne King 2012 年 12 月 14 日
Don't assign like this:
txt{'i'}
assign like this
txt{i}
For example
for ii =1:length(txt)
if isequal(txt{ii},'BBB3')
txt{ii}=11;
elseif isequal(txt{ii},'BBB2')
txt{ii}=12;
elseif isequal(txt{ii},'BBB1')
txt{ii}=13;
elseif isequal(txt{ii},'A3')
txt{ii}=14;
elseif isequal(txt{ii},'A2')
txt{ii}=15;
elseif isequal(txt{ii},'A1')
txt{ii}=16;
elseif isequal(txt{ii},'AA3')
txt{ii}=17;
elseif isequal(txt{ii},'AA2')
txt{ii}=18;
else
txt{ii}=20;
end
end
  1 件のコメント
Saad
Saad 2012 年 12 月 14 日
Thanks a lot it is working now...thank you for your help

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

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by