2

我在matlab中有结构和结构数组,例如:

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

是否可以以矢量方式进行操作?

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

更新:
感谢您的回复。实际上,我问的是“简单”(意思是“矢量方式”)。现在我看到使用结构是不可能的。所以唯一的方法是使用 DreamBig 建议的类似 arrayfun 的东西。或者使用数组结构。

4

1 回答 1

0

您可以创建一个自定义类来执行您想要的操作。该类将包含 'Val1作为属性。它将通过放置 +一个名为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

以下是如何使用它:

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

同样,您可以覆盖乘法运算符。

于 2014-12-28T12:43:19.157 回答