[英]How to tell octave that the index is meant to be a matrix, not a vector
When indexing into a vector with a matrix of variable dimensions, how do I indicate to octave that the index is a matrix and not a vector? 当索引具有可变尺寸矩阵的向量时,如何指示八度索引是矩阵而不是向量?
For example, in the following code, on the fourth iteration, Octave sees the index as a row-vector and it transposes the return value of the indexing operation to be a column vector (to match the vector being indexed into rather than the one used for indexing). 例如,在下面的代码中,在第四次迭代中,Octave将索引视为行向量,并且将索引操作的返回值转置为列向量(以匹配被索引的向量,而不是所使用的向量)。用于索引)。
When I run: 当我跑步时:
v = rand(16,1);
t = magic(4);
f = @(m)(sum(m, 1));
for i = 4:-1:1
s = t(1:i,:);
f(v(s))
endfor
I get: 我得到:
ans =
1.47780 2.28879 1.29786 2.98981
ans =
1.24705 1.31940 0.87484 2.18276
ans =
0.89387 0.55288 0.50312 1.61950
ans = 1.9294
See that on the first three iterations, the answer is a row-vector, but on the last iteration, the answer is a singleton value. 看到在前三个迭代中,答案是行向量,但是在最后一个迭代中,答案是单例值。
How do I tell octave that the variable s is supposed to be a matrix, not a vector and that the result of the indexing operation should always be the same shape as s? 我该如何告诉octave变量s应该是矩阵,而不是向量,并且索引操作的结果应始终与s形状相同?
One way to work around this "feature" would be something like this: 解决此“功能”的一种方法是这样的:
v = rand(16,1);
t = magic(4);
f = @(m)(sum(m, 1));
for i = 4:-1:1
w(1:i,:) = v(t(1:i,:));
f(w(1:i,:))
end
This forces the output of v
to be stored in w
in the proper orientation. 这迫使v
的输出以正确的方向存储在w
中。 Note that I pass w(1:i,:)
into the function f
rather than just w
because of your reverse-indexed for
loop. 请注意,我通过w(1:i,:)
入函数f
而不仅仅是w
因为你的反向索引for
循环。
This is a surprising common pattern and is a useful way of repeatedly setting the columns of a matrix equal to a row vector or the rows of a matrix equal to a column vector without needing to perform a transpose or even know the orientation of the vector (who knows the the Matlab/Octave JITs do under the hood). 这是一种令人惊讶的常见模式,并且是重复设置矩阵的列等于行向量或矩阵的行等于列向量的有用方法,而无需执行转置甚至不知道向量的方向(谁知道Matlab / Octave JIT在幕后做了什么?
How do I tell octave that the variable s is supposed to be a matrix, not a vector 如何告诉八度,变量s应该是矩阵,而不是向量
In Matlab/Octave matrix and vector is the same thing. 在Matlab / Octave中,矩阵和矢量是同一回事。 Vector is just a 1xm or mx1 matrix. 向量只是一个1xm或mx1矩阵。
In sum function dimension option only works if both dimensions are bigger than 1. 总和函数维选项仅在两个维都大于1时才有效。
Just make vector a special case. 只是使vector成为特例。
for i = 4:-1:1
s = t(1:i,:);
if i~=1
f(v(s))
else
v(s)'
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.