我想检索沿着N维数组A的最后一个维度的所有元素。也就是说,如果idx是一个(N-1)维元组,我想要A[idx...,:]
。我已经弄明白了如何使用CartesianRange,它的工作方式如下所示
A = rand(2,3,4)
for idx in CartesianRange(size(A)[1:end-1])
i = zeros(Int, length(idx))
[i[bdx] = idx[bdx] for bdx in 1:length(idx)]
@show(A[i...,:])
end
但是,必须有一种更简单的方法来创建上面显示的索引。 Splatting idx不起作用 - 我做错了什么?
答案 0 :(得分:2)
您可以直接使用从CartesianRange生成的CartesianIndex进行索引!
function getNumber(array) {
var counter = 0,
landline = '',
second = '';
array.some(function (o) {
if (o.type === 'landline') {
landline = o.number;
return true;
}
counter++;
if (counter === 2) {
second = o.number;
}
});
return landline || second;
}
//should return the third number for this array
var phoneObject1 = [{ type: 'mobile', number: '0123456789' }, { type: 'mobile', number:'78945610' }, { type: 'landline', number:'15975345' }];
// for this one it should return the first
var phoneObject2 = [{ type: 'landline', number: '0123456789' }, { type: 'mobile', number:'78945610' }, { type:'landline', number:'15975345' }];
// for this one it should return the second number
var phoneObject3 = [{ type: 'mobile', number: '0123456789' }, { type: 'mobile', number:'78945610' }];
//and for this last one it should return a blank value
var phoneObject4 = [{ type: 'mobile', number: '0123456789' }];
console.log([phoneObject1, phoneObject2, phoneObject3, phoneObject4].map(getNumber));
我在此处提出的另一个建议是使用未导出的julia> for idx in CartesianRange(size(A)[1:end-1])
@show(A[idx,:])
end
A[idx,:] = [0.0334735,0.216738,0.941401,0.973918]
A[idx,:] = [0.842384,0.236736,0.103348,0.729471]
A[idx,:] = [0.056548,0.283617,0.504253,0.718918]
A[idx,:] = [0.551649,0.55043,0.126092,0.259216]
A[idx,:] = [0.65623,0.738998,0.781989,0.160111]
A[idx,:] = [0.177955,0.971617,0.942002,0.210386]
函数从Base.front
中提取前导维度,而不是将其编入索引。在这样的type-stable way中处理元组可能有点棘手,但是一旦掌握了它,它们就会非常快。
值得注意的是,Julia的数组是列专业的,因此像这样访问尾随维是going to be much slower而不是抓取列。