Accessing the string elements

조회 수: 60 (최근 30일)
pradeep kumar
pradeep kumar 2017년 10월 17일
편집: Cedric 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
KL 2017년 10월 17일
You're defining three entirely different variables. Where and how do you want to apply this?
Stephen23
Stephen23 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:

댓글을 달려면 로그인하십시오.

채택된 답변

Cedric
Cedric 2017년 10월 17일
편집: Cedric 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
pradeep kumar
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
Cedric 2017년 10월 17일
편집: Cedric 2017년 10월 17일
Awesome. Thank you for the positive feedback!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by