2

I have struct and array of structs in matlab like:

s.name = 'pop';     
s.val1 = 2.3;  
s.val2 = 4.3;
q = repmat( s, 5, 5 );    

Is it possible to do operations in vectorial-way?

%// Something like this?
q(:,:).val1 = q(:,:).val1 + q(:,:).val2 * 0.2;

Upd:
Thanks for replies. Actually, I was asking about "simple" (with meaning "vectorial-way"). Now I see it's impossible using structures. So the only way is to use something like arrayfun suggested by DreamBig. Or use structure of arrays.

Suever
  • 64,497
  • 14
  • 82
  • 101
qloq
  • 689
  • 1
  • 5
  • 15

1 Answers1

0

You can create a custom class that will do what you want. The class will contain 'Val1 as property. It will override + operator by putting a function called plus.

classdef MyStruct 
    properties
        Val1
    end

    methods
        function this = MyStruct(val1)
            if nargin ~= 0 % Allow nargin == 0 syntax
                m = numel(val1);
                this(m) = MyStruct(); % Preallocate object array
                for i = 1:m
                    this(i).Val1 = val1(i);
                end
            end
        end

        function outRes = plus(this,other)
            outRes(numel(this.Val1))=MyStruct();
            for i=1:numel(this)
                outRes(i).Val1 = this(i).Val1 + other(i).Val1;
            end
        end
    end
end

And here is how to use it:

m1 = MyStruct(1:3); 
m2 = MyStruct([0 1 5]);
m3 = m1 + m2;

Similarly, you can override multiplication operator.

Andrey Rubshtein
  • 20,795
  • 11
  • 69
  • 104