Ok actually, cycling through all workspace variables is not considered a best practice. If your workspace contains a lot of variables, and a majority of them are not necessary for your calculations, you are just gonna spend a lot of time to accomplish this task with no reason.
There must be a moment in which you allocate / instantiate those classes in your code, and that would be a great moment to insert them into different cell arrays that hold the different exiting categories of objects. That way, you will just have to apply your code to all the instances inside the target cell arrays to obtain the desired result.
Another good idea is to create a superclass called, for example, Vehicle, that both Car and 'Plane' classes will inherit. Then, you can define your function calculateSpeed into the superclass, so you can keep on working on generic class profiles and avoid checking many different type of classes. But this would be tricky if you insist on sticking with cycling workspace variables.
Option 1 with workspace variables:
% Animal Categories
classdef Animal < handle
% ...
end
% Vehicle Categories
classdef (Abstract) Vehicle < handle
properties
Speed
end
methods
function CalculateSpeed(this)
this.Speed = 100; % your calculations here
end
end
end
classdef Car < Vehicle
% ...
end
classdef Plane < Vehicle
% ...
end
% Script Code
Ford = Car();
VW = Car();
Boeing = Plane();
car = Animal();
vars = whos();
for i = 1:numel(vars)
var_curr = vars(i);
if (strcmp(var_curr.class,'Car') || strcmp(var_curr.class,'Plane'))
eval([var_curr.name '.CalculateSpeed()']);
end
end
Option 2 with full control over instances allocation:
% Animal
classdef (Abstract) Animal < handle
% ...
end
% Vehicle
classdef Vehicle < handle
properties
Name
Speed
Type
end
methods
function this = Vehicle(type,name)
this.Type = type;
this.Name = name;
this.CalculateSpeed();
end
end
methods
function CalculateSpeed(this)
switch (this.Type)
case 'Car'
this.Speed = 50;
case 'Plane'
this.Speed = 150;
otherwise
this.Speed = 0;
end
end
end
end
% Script Code
insts = cell(10,1);
for i = 1:10
insts{i} = Vehicle(type,name);
end
If you don't want to calculate the speeds directly when the object is instantiated, then just comment the call to the method in the constructor and run a loop to do it when necessary:
for i = 1:10
insts{i}.CalculateSpeed();
end
Option 3, let's keep using your idea:
vars = whos();
for i = 1:numel(vars)
var_curr = vars(i);
if (strcmp(var_curr.class,'Car') || strcmp(var_curr.class,'Plane'))
s = eval(['calculateSpeed(' var_curr.name ')']);
end
end
On a side note, logical operators in if conditions must be double. Single logical operators can only be used between two logical operators in an indexing context. Also, always try to cache your indexing results because for loops in Matlab are expensive, and this can save up a lot of time in big cycles.