通过for循环“填充”Matlab中的空向量

时间:2015-12-04 17:25:42

标签: matlab loops for-loop vector vectorization

我正在尝试在MATLAB中创建一个循环代码,用于“填充”大小为 l x 1 的空列向量中的元素,称为 m 。由于我在MATLAB方面没有太多经验,所以我不确定这是否是正确的方法。

注意:看作 i 属于matlab中的复杂数量,我将数组的 i-th 元素表示为< em> ii-th 元素。

l=length(A);         %The number of rows in the empty vector we seek as our output;
                     %so as to preallocate space for this vector.

q=eigencentrality(A);%An lx1 column vector whose ii-th elements are used in the loop.
l1=max(eig(A));      %A scalar used in the loop.
CS=sg_centrality(A); %%An lx1 column vector whose ii-th elements are used in the loop.

                     %Now for the actual loop that will "fill up" each ii-th entry
                     %of our empty vector, m.

m=NaN(l,1);          %create the empty vector to be "filled up".
for ii=1:l
   m(ii,:)=log(q(ii)^2)*sinh(l1)/CS(ii)^1/2;%this is the form that I want each entry
                                            %of m to have. Note how the ii-th element
                                            %of m depends on the corresponding ii-th
                                            %element of CS and q!
end

这是否是“填充”这样一个空列向量 m 的正确方法,其条目取决于上述两个其他向量的对应元素?

干杯!

2 个答案:

答案 0 :(得分:4)

你可以完全矢量化。矢量化是一次处理数据块的行为,而不是像在代码中那样单独处理数据块。实际上,这是MATLAB的主要优势之一。您可以将for循环替换为:

 m = log(q.^2).*(sinh(l1)./CS).^1/2;

.*.^运算符称为元素明细运算符。这意味着qliCS中的每个值都会影响输出中的相应位置。没有必要使用循环。

在此处查看有关矢量化的MathWorks注释:http://www.mathworks.com/help/matlab/matlab_prog/vectorization.html

答案 1 :(得分:4)

您可以矢量化所有操作,而无需使用for循环。这应该有效:

m=log(q.^2).*(sinh(l1)./CS).^1/2;

注意,点表示元素操作。通常这比使用循环要快得多。另外,作为旁注,您可以放弃预分配。