Assignment in a for loop
1 次查看(过去 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 个评论
采纳的回答
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!