How to edit original data in for-each equivalent statement

1 view (last 30 days)
I'm working with nested classes for Object Oriented Programming (OOP) and trying to find a cleaner way of doing things. For example, the following code is a function of a class Attacker which is a pain to read where Attacker has a property filtered_database which is a class which has vulns which has profile which has props which has scaled_value. Embedded classes like this are the norm for OOP, but using an indexed iteration scheme is just not nice and when you have 1000 lines of code the migranes set in.
% Loop through each vulnerability
for i=1:length(obj.filtered_database.vulns)
temp_profile = obj.filtered_database.vulns(i).profile;
% Scale each property
for j=1:length(temp_profile.props)
scaled_val = obj.ScaleProperty(temp_profile.props(j));
obj.filtered_database.vulns(i).profile.props(j).scaled_value = scaled_val;
So I'm trying to use the more functional component of the for loop. Take the example:
People = {'Joe', 'Bill', 'Ted'}
for person = People
person = strcat(person,' Foo');
If we were in python, person would be recognized as a linked part of the People object within the for-loop, meaning any changes I make to person would be reflected in People after completion of the for-loop, but this is not the case in Matlab. Now, in order to update the values in People, I need some sort of counter to keep track of which item in People I'm looking at. Is there a standard way of modifying the value in People in the loop as you would in Python without a counter? Any help would be appreciated.

Accepted Answer

Greg Dionne
Greg Dionne on 18 Oct 2019
Edited: Greg Dionne on 18 Oct 2019
You can often avoid the need for references and the for-loop altogether in MATLAB.
This example should get you started:
classdef myClass
Number = 0
Person = 'Unknown'
Example usage:
x = repmat(myClass,3,1)
people = {'Joe','Bill','Ted'};
numArray = [7,5,4];
% convert numbers to cell arrays
numbers = num2cell(numArray);
% use comma-separated lists to do the assignment
[x.Person] = people{:};
[x.Number] = numbers{:};
% display each class element
% assign a range
people = {'Jack','Jill'};
[x(2:3).Person] = people{:};
Take a look at the documentation for comma-separated lists.
  1 Comment
C Delog
C Delog on 21 Oct 2019
This is a step forward. Even though MATLAB claims to be capable of object-oriented programming, it seems like object-affiliated programming would be more accurate :) But I recognize that MATLAB's MO tends be toward applying vector computations to eliminate loops as much as possible and your solution seems to fall in-line with that. I'll apply this and see what 1000 lines look like without as many for-loops. Many thanks.

Sign in to comment.

More Answers (0)


Find more on Loops and Conditional Statements in Help Center and File Exchange




Community Treasure Hunt

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

Start Hunting!