Assignment in a for loop
5 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponses (1)
Stephen23
le 19 Août 2021
Modifié(e) : Stephen23
le 19 Août 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
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!