MATLAB Answers

Translated by

このページのコンテンツは英語から自動翻訳されています。自動翻訳をオフにする場合は「<a class="turn_off_mt" href="#">ここ</a>」をクリックしてください。

0

Accessing the string elements

pradeep kumar さんによって質問されました 2017 年 10 月 17 日
最新アクティビティ Cedric Wannaz
さんによって 編集されました 2017 年 10 月 17 日
I have 3 strings like the following:
world=["America", "Europe"]; % Parent String
America=["USA", "Brazil", "Argentina"]; % Child1 String
Europe=["France", "Germany", "England"]; % Child2 String
I want to access the elements of the child string (Country names) from the Parent string(world) and use it inside a for loop for further operation. I am trying in the following way:
for i=1:2
d=world(i); % Temporary variable to store the continent name
for j=1:3
disp(d(j)); % Throws an Error: "Index exceeds Matrix dimensions
end
end
What am I doing wrong? Any help will be highly appreciated.

  2 件のコメント

KL
2017 年 10 月 17 日
You're defining three entirely different variables. Where and how do you want to apply this?
Stephen Cobeldick
2017 年 10 月 17 日
The simplest and most efficient solution is to use structures and dynamic fields:
Do not try to magically access variable names. Doing so will make your code slow, complex, buggy, hard to debug, inscure. Read this to know why:

サインイン to comment.

製品

1 件の回答

Cedric Wannaz
回答者: Cedric Wannaz
2017 年 10 月 17 日
編集済み: Cedric Wannaz
2017 年 10 月 17 日
 採用された回答

Here is one way, as string arrays are "iterable".
continents = ["America", "Europe"] ;
countries.America = ["USA", "Brazil", "Argentina"] ;
countries.Europe = ["France", "Germany", "England"] ;
for continent = continents
fprintf('%s :\n', continent ) ;
for country = countries.(continent)
fprintf('\t%s\n', country) ;
end
end
Yet, using dynamic field names for that is usually not advised. You could use cell arrays instead:
continents = {"America", "Europe"} ;
countries{1} = {"USA", "Brazil", "Argentina"} ;
countries{2} = {"France", "Germany", "England"} ;
for continentId = 1 : numel( continents )
fprintf('%s :\n', continents{continentId} ) ;
for countryId = 1 : numel( countries{continentId} )
fprintf('\t%s\n', countries{continentId}{countryId} ) ;
end
end

  9 件のコメント

Cedric Wannaz
2017 年 10 月 17 日
Pradeep, which version of MATLAB are you using, it is < 2016b ? Do you really need to use strings by the way? Does the following work?
continents = ["America", "Europe"] ;
countries.America = ["USA", "Brazil", "Argentina"] ;
countries.Europe = ["France", "Germany", "England"] ;
for continent = continents
fprintf('%s :\n', continent ) ;
for country = countries.(char(continent))
fprintf('\t%s\n', country) ;
end
end
pradeep kumar 2017 年 10 月 17 日
Cedric, The above solution works perfect. I am using MATLAB 2017a. You are genius. Thanks a lot. I hope, You were my TEACHER here.
Cedric Wannaz
2017 年 10 月 17 日
Awesome. Thank you for the positive feedback!

サインイン to comment.



Translated by