How to edit original data in for-each equivalent statement
1 次查看(过去 30 天)
显示 更早的评论
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;
end
end
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');
end
People
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.
0 个评论
采纳的回答
Greg Dionne
2019-10-18
编辑:Greg Dionne
2019-10-18
You can often avoid the need for references and the for-loop altogether in MATLAB.
This example should get you started:
classdef myClass
properties
Number = 0
Person = 'Unknown'
end
end
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
x(1)
x(2)
x(3)
% assign a range
people = {'Jack','Jill'};
[x(2:3).Person] = people{:};
x(2)
x(3)
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Scope Variables and Generate Names 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!