分配具有多个条件的值

gme*_*oni 3 matlab matrix

我们有一个M = [10 x 4 x 12]矩阵.作为例子,我采取M(:,:,4):

val(:,:,4) =

     0     0     1     0
     0     1     1     1
     0     0     0     1
     1     1     1     1
     1     1     0     1
     0     1     1     1
     1     1     1     1
     1     1     1     1
     0     0     1     1
     0     0     1     1
Run Code Online (Sandbox Code Playgroud)

我怎样才能得到这个:

val(:,:,4) =

     0     0     3     0
     0     2     2     2
     0     0     0     4
     1     1     1     1
     1     1     0     1
     0     2     2     2
     1     1     1     1
     1     1     1     1
     0     0     3     3
     0     0     3     3
Run Code Online (Sandbox Code Playgroud)
  • 如果我在第一列中有1,那么所有后续的1应该是1.
  • 如果我在第一列中有0但在第二列中有1,则后续1的所有1应为2.
  • 如果我在第一列和第二列中有0但在第三列中有1,则所有后续的1应该是3.
  • 如果我在前3列中有0但在第4列中有1则那么这个应该是4.

注意:M构造逻辑矩阵:

Tab = [reshape(Avg_1step.',10,1,[]) reshape(Avg_2step.',10,1,[]) ...
    reshape(Avg_4step.',10,1,[]) reshape(Avg_6step.',10,1,[])];

M = Tab>=repmat([20 40 60 80],10,1,size(Tab,3));
Run Code Online (Sandbox Code Playgroud)

Ste*_*fin 5

这是一种非常简单的方法,适用于2D和3D矩阵.

%// Find the column index of the first element in each "slice".
[~, idx] = max(val,[],2);  

%// Multiply the column index with each row of the initial matrix
bsxfun(@times, val, idx);
Run Code Online (Sandbox Code Playgroud)

  • 有趣而聪明的方法! (2认同)