0

So I have a class let's call it MyClass which has 3 properties, a value, valueMinus1 and valuePlus1. These two properties hold the neighboring values in an array of classes. Is there a good way to update these (it will be done iteratively as value changes). There is the simple way:

%//initialize the class array
class_array = MyClass.empty(n,0);
for i=1:n
  class_array(i) = MyClass(i); % //just put in the index at value
end

%//now update the valuePlus1 and valueMinus1 properties
for i=1:n
  if i==1
    class_array(i).valueMinus1 = class_array(end).value;
  else
    class_array(i).valueMinus1= class_array(i-1).value
  end

  if i==n
    class_array(i).valuePlus1 = class_array(1).value
  else
    class_array(i).valuePlus1 = class_array(i+1).value
  end

But I feel like there must be a better, more clever and more efficient way to do this.

Raab70
  • 721
  • 3
  • 11

1 Answers1

0

You can use the modulus operator instead of if else statements. That will simplify it a little.

for i=1:n
    class_array(i).valueMinus1= class_array(mod(i-2,n)+1).value
    class_array(i).valuePlus1 = class_array(mod(i,n)+1).value
end

Does this answer your question?

Trogdor
  • 1,346
  • 9
  • 16
  • I was hoping to do it vectorized but I don't think that is possible based on this answer: http://stackoverflow.com/questions/17112310/setting-object-properties-value-for-object-array-in-matlab I think this answer is the best that it gets. Thanks. – Raab70 Aug 21 '14 at 19:22