How to change some specific fields of a structure without using for loop in matlab?

46 views Asked by At

Lets suppose, we have a structure and want to change the same field in some desired indexes without using costly for loops. Can anyone suggest a solution to do it?

An example:

Lets suppose we have a structure which is called student, and we want to change the field 'average' for (student no#125, no#231, no#245, no#256 and so on) when it is necessary. Then as i know we should write it as below:

should2change = [125, 231, 245, 256, ....];

for i = 1:numel(should2change)

   student(should2change(i,1)).average = student(should2change(i,1)).average + 1;

end

is there a straightforward way to avoid using this kind of costly for loops while doing exactly the same task?

1

There are 1 answers

2
hiddeninthewifi On

As far as I know, there's not a very good way to get around a for loop -- if you don't know what elements you'll access ahead of time. However, if you really want to, you can do what is called loop unrolling, where you write the instruction out x number of times instead of doing a for loop x times. So, for instance, if you know that should2change (s2c here) will always have 5 items, you can do:

student(s2c(1,1).average = s2c(1,1).avg+1
student(s2c(2,1).average = s2c(2,1).avg+1
student(s2c(3,1).average = s2c(3,1).avg+1
student(s2c(4,1).average = s2c(4,1).avg+1
student(s2c(5,1).average = s2c(5,1).avg+1

Perhaps this could be parallelized, but unless it really will boost performance, I wouldn't worry.

I don't think that's what you're going for though, in which case, a for loop is probably best. But for loops aren't too costly in matlab. The only time you really have to start worrying about it is if you start nesting for loops (always a bad idea.)