Assignment in a for loop
조회 수: 2 (최근 30일)
이전 댓글 표시
Hi,
I think I have a simple problem but I cant handle it to be honest. Here is a minmal example
classdef SoccerLeague<handle
properties
player1=struct('Name','','Position',[],'GP',[],'PF',[],'PA',[],'P',[])
player2=struct('Name','','Position',[],'GP',[],'PF',[],'PA',[],'P',[])
player3=struct('Name','','Position',[],'GP',[],'PF',[],'PA',[],'P',[])
player4=struct('Name','','Position',[],'GP',[],'PF',[],'PA',[],'P',[])
% player5=struct('Name','','Position',[],'GP',[],'PF',[],'PA',[],'P',[])
% player6=struct('Name','','Position',[],'GP',[],'PF',[],'PA',[],'P',[])
% player7=struct('Name','','Position',[],'GP',[],'PF',[],'PA',[],'P',[])
% player8=struct('Name','','Position',[],'GP',[],'PF',[],'PA',[],'P',[])
end
methods
function obj=SoccerLeague
players={'Joe','John','Lisa','Tina'};
for ii=1:length(players)
obj.['player' num2str(ii)].Name=players{ii}
end
end
end
end
I have 4 properties (player1 to player 4 )which are structs and in the constructor function I want to assign them the corresponing names which are incorporated in the variable players. I would like to accomplish this with a simple for loop but i have no idea how to loop through the property names player1....player4. Obviously my try above does not work. I also tried to use the eval function but it did not work.
So at the end there should be obj.player1.Name=Joe .... obj.player4.Name=Tina assigned in a for loop.
Any suggestion how to solve this simple looking problem?
Thanks in advance...
댓글 수: 0
답변 (1개)
Stephen23
2021년 8월 19일
편집: Stephen23
2021년 8월 19일
"Any suggestion how to solve this simple looking problem?"
Use a non-scalar structure:
Rather than awkwardly and inefficiently forcing meta-data (a pseudo-index) into the property names, a simple non-scalar structure would let you use neat, basic, efficient MATLAB indexing to achieve your goal:
classdef SoccerLeague<handle
properties
% Empty structure:
players = struct('Name',{},'Position',{},'GP',{},'PF',{},'PA',{},'P',{});
end
methods
function obj = SoccerLeague
names = {'Joe','John','Lisa','Tina'};
for ii = 1:numel(names)
obj.players(ii).Name = names{ii};
end
end
end
end
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!