2
votes

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.

1
using cells in place of a structure - yakoudbz
You could do something like... temp = arrayfun(@(x, y) plus(x, y), [q.val1], [q.val2]*0.2, 'UniformOutput', false); and then assigning it as [q.val1] = deal(temp{:}) - DreamBig
For vector operations you should use a vector or matrix, not a struct - Luis Mendo
@DreamBig - Ah deal... very nice. - rayryeng

1 Answers

0
votes

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.