结构的Matlab数组:快速赋值

sum*_*dds 11 arrays matlab struct vectorization variable-assignment

有没有办法"vector"分配一个struct数组.

目前我可以

edges(1000000) = struct('weight',1.0); //This really does not assign the value, I checked on 2009A.
for i=1:1000000; edges(i).weight=1.0; end; 
Run Code Online (Sandbox Code Playgroud)

但这很慢,我想做更多的事情

edges(:).weight=[rand(1000000,1)]; //with or without the square brackets. 
Run Code Online (Sandbox Code Playgroud)

任何想法/建议来矢量化这个任务,以便它会更快.

提前致谢.

小智 13

这比交易或循环要快得多(至少在我的系统上):

N=10000;
edge(N) = struct('weight',1.0); % initialize the array
values = rand(1,N);  % set the values as a vector

W = mat2cell(values, 1,ones(1,N)); % convert values to a cell
[edge(:).weight] = W{:};
Run Code Online (Sandbox Code Playgroud)

在右边使用花括号给出了W中所有值的逗号分隔值列表(即N个输出),右边使用方括号将这些N个输出分配给edge(:).weight中的N个值.


Aab*_*baz 9

您可以尝试使用Matlab函数deal,但我发现它需要稍微调整一下输入(使用这个问题:在Matlab中,对于多输入函数,如何使用单个输入作为多个输入?),也许有一些更简单的东西.

n=100000;
edges(n)=struct('weight',1.0);
m=mat2cell(rand(n,1),ones(n,1),1);
[edges(:).weight]=deal(m{:});
Run Code Online (Sandbox Code Playgroud)

另外我发现这并不像我的计算机上的for循环那么快(约为0.35s,因为交易约为0.05s)可能是因为调用了mat2cell.如果你不止一次使用它,速度的差异会减少,但它仍然支持for循环.

  • 这是我的时代.在Octave上:对于这种方法,对于100K为0.17秒,对于1mil为1.57s,如果我使用for循环,则需要使用,例如230s用于100K.MATLAB 2009B(diff machine/OS):使用上面的5s/49s和使用for循环的.22s/2.2s. (2认同)

Amr*_*mro 7

你可以简单地写:

edges = struct('weight', num2cell(rand(1000000,1)));
Run Code Online (Sandbox Code Playgroud)