在MATLAB中检索spfun,cellfun,arrayfun等中的元素索引 [英] Retrieving element index in spfun, cellfun, arrayfun, etc. in MATLAB
问题描述
是否有任何方法可以检索由cellfun
,arrayfun
或spfun
调用的函数所作用的元素的 index ? (即在函数范围内检索元素的索引).
Is there any way to retrieve the index of the element on which a function called by cellfun
, arrayfun
or spfun
acts? (i.e. retrieve the index of the element within the scope of the function).
为简单起见,假设我有以下玩具示例:
For the sake of simplicity, imagine I have the following toy example:
S = spdiags([1:4]',0,4,4)
f = spfun(@(x) 2*x,S)
建立一个4x4的稀疏对角矩阵,然后将每个元素乘以2
.
which builds a 4x4 sparse diagonal matrix and then multiplies each element by 2
.
然后说,现在,我不想将每个元素乘以常数2
,而是将其乘以元素在原始矩阵中的索引,即假设
And say that now, instead of multiplying each element by the constant number 2
, I would like to multiply it by the index the element has in the original matrix, i.e. assuming that linear_index
holds the index for each element, it would be something like this:
S = spdiags([1:4]',0,4,4)
f = spfun(@(x) linear_index*x,S)
但是,请注意上面的代码不起作用(未声明linear_index
).
However, note the code above does not work (linear_index
is undeclared).
这个问题部分是由blocproc
允许您访问block_struct.location
的事实引起的,该事实可能会引起人们引用当前元素在内的位置(〜索引).完整对象(在这种情况下为图片):
This question is partially motivated by the fact that blocproc
gives you access to block_struct.location
, which one could argue references the location (~index) of the current element within the full object (an image in this case):
block_struct.location:
一个由两个元素组成的向量[row col],用于指定 像素的第一个像素(最小行,最小列)的位置 阻止输入图像中的数据.
block_struct.location:
A two-element vector, [row col], that specifies the position of the first pixel (minimum-row, minimum-column) of the block data in the input image.
推荐答案
否,但是您可以提供线性索引作为额外的参数.
No, but you can supply the linear index as extra argument.
cellfun
和arrayfun
都接受多个输入数组.因此,例如arrayfun,你可以写
Both cellfun
and arrayfun
accept multiple input arrays. Thus, with e.g. arrayfun, you can write
a = [1 1 2 2];
lin_idx = 1:4;
out = arrayfun(@(x,y)x*y,a,lin_idx);
不幸的是,这不适用于spfun
,因为它仅接受单个输入(稀疏数组).
This doesn't work with spfun
, unfortunately, since it only accepts a single input (the sparse array).
您可以改用arrayfun
,如下所示:
You can possibly use arrayfun
instead, like so:
S = spdiags([1:4]',0,4,4);
lin_idx = find(S);
out = spones(S);
out(lin_idx) = arrayfun(@(x,y)x*y,full(S(lin_idx)),lin_idx);
%# or
out(lin_idx) = S(lin_idx) .* lin_idx;
请注意,对full
的调用不会使您陷入内存麻烦,因为S(lin_idx)
的稀疏度为0%.
Note that the call to full
won't get you into memory trouble, since S(lin_idx)
is 0% sparse.
这篇关于在MATLAB中检索spfun,cellfun,arrayfun等中的元素索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!