Assignment in a for loop

12 visualizzazioni (ultimi 30 giorni)
René Lampert
René Lampert il 19 Ago 2021
Commentato: darova il 19 Ago 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...

Risposte (1)

Stephen23
Stephen23 il 19 Ago 2021
Modificato: Stephen23 il 19 Ago 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 Commenti
René Lampert
René Lampert il 19 Ago 2021
thanks for the fast response. This is definetly a legit solution.
darova
darova il 19 Ago 2021

Accedi per commentare.

Community Treasure Hunt

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

Start Hunting!

Translated by