Matlab矩阵中每行的最后一个正元素

时间:2017-03-22 19:20:36

标签: matlab

我想在Matlab中找到维度X的矩阵wxy中每行的最后一个正元素。

rng default;  

%if w=1, then the code below works
A=sort(randn(1,20), 'descend');
idx=find(A>=0, 1, 'last');

%if w>1, how can I proceed?
A=sort(randn(8000,20),2, 'descend');
%idx=?
%I am expecting idx=[12;5;8;...]

你能帮我一个非常有效的代码吗?

4 个答案:

答案 0 :(得分:1)

对于您的标题的一般答案比您的具体案例的答案更难。在您的示例中,您似乎要求“Matlab矩阵中每行的最后一个正元素,其中每行按降序排序”。这相当于要求“每行中最小的正值”,这可以在不进行排序的情况下完成:

function [val, ind] = smallest_positive(A, dim)

if nargin < 2, A = A(:); dim = 1; end
A(A <= 0) = inf;
[val, ind] = min(A, [], dim);

使用示例:

>> A = randn(3, 8)

A =

    0.7990    0.2120   -0.7420    0.3899   -0.5596    0.7812   -0.2656    0.9863
    0.9409    0.2379    1.0823    0.0880    0.4437    0.5690   -1.1878   -0.5186
   -0.9921   -1.0078   -0.1315   -0.6355   -0.9499   -0.8217   -2.2023    0.3274

>> [val, ind] = smallest_positive(A, 2)

val =

    0.2120
    0.0880
    0.3274


ind =

     2
     4
     8

请注意,这只返回每行的“最后”正值,意思是“如果您要执行sort”将是最后一个值。如果你真的想要每一行的最后一个正值,无论是否排序,那么Divakar的回答就是你要做的。

答案 1 :(得分:1)

rng default;  

A=sort(randn(8000,20),2, 'descend');
idx = sum(A>=0, 2);

实际上你不需要排序。

A = randn(8000,20);
idx = sum(A>=0, 2);

答案 2 :(得分:1)

我能想到的最简单的解决方案(给定A已排序):

[~,idx] = min(A>=0,[],2);   % Returns the first indices of the zero entries
idx = idx-1;               % Get the indices before the first zero entries

答案 3 :(得分:1)

基于问题标题,我正在解决一般情况并且不对输入进行排序或其他方面做出假设。

这里的想法是翻转行并与zero进行比较,然后沿每行获取argmax,然后通过从行长度中减去来补偿翻转 -

[~,idx] = max(a(:,end:-1:1)>=0,[],2);
out = size(a,2) - idx + 1

要获得相应的元素,只需获取线性索引和索引 -

a_last = a((out-1)*size(a,1) + [1:size(a,1)]')

示例运行 -

>> a
a =
    1.6110    0.0854   -0.8777    0.6078    0.0544   -0.4089    0.0675
    0.7708    1.6510    0.1572   -0.7475    0.0218   -0.8292    1.0934
   -0.4704    1.2351    1.2660    2.2117   -0.3616   -0.9500   -0.7682
    0.8539   -0.5427   -1.0213    0.2489   -1.6312    0.0723    0.1284
    1.5050    1.4430    1.1947    0.2846   -1.2621    0.5518    1.4290
    0.1785    1.1087   -0.0225    1.1447    0.2316   -0.2431   -1.2750
    0.3089    1.5716   -1.9958    0.0015    1.5448   -0.0750    0.4965
    0.3593    0.8143    0.4389   -0.2541    0.1558   -0.2965    0.7111
>> [~,idx] = max(a(:,end:-1:1)>=0,[],2);
>> out = size(a,2) - idx + 1
out =
     7
     7
     4
     7
     7
     5
     7
     7
>> a((out-1)*size(a,1) + [1:size(a,1)]')
ans =
    0.0675
    1.0934
    2.2117
    0.1284
    1.4290
    0.2316
    0.4965
    0.7111