MATLAB Answers

Assignment in a for loop

1 view (last 30 days)
René Lampert
René Lampert on 19 Aug 2021
Commented: darova on 19 Aug 2021
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...

Answers (1)

Stephen
Stephen on 19 Aug 2021
Edited: Stephen on 19 Aug 2021
"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
  2 Comments

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!