使用/ multiple条件分配值

时间:2015-01-28 08:48:24

标签: 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

我怎样才能获得这个:

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
  • 如果我在第一列中有1,那么随后的所有1应该是1.
  • 如果我在第一列中有0但在第二列中有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));

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:1)

这可能是一种方法 -

%// Concatenate input array along dim3 to create a 2D array for easy work ahead 
M2d = reshape(permute(M,[1 3 2]),size(M,1)*size(M,3),[]);

%// Find matches for each case, index into each matching row and
%// elementwise multiply all elements with the corresponding multiplying
%// factor of 2 or 3 or 4 and thus obtain the desired output but as 2D array
%// NOTE: Case 1 would not change any value, so it was skipped.
case2m = all(bsxfun(@eq,M2d(:,1:2),[0 1]),2);
M2d(case2m,:) = bsxfun(@times,M2d(case2m,:),2);

case3m = all(bsxfun(@eq,M2d(:,1:3),[0 0 1]),2);
M2d(case3m,:) = bsxfun(@times,M2d(case3m,:),3);

case4m = all(bsxfun(@eq,M2d(:,1:4),[0 0 0 1]),2);
M2d(case4m,:) = bsxfun(@times,M2d(case4m,:),4);

%// Cut the 2D array thus obtained at every size(a,1) to give us back a 3D
%// array version of the expected values
Mout = permute(reshape(M2d,size(M,1),size(M,3),[]),[1 3 2])

使用随机6 x 4 x 2大小的输入数组运行代码 -

M(:,:,1) =
     1     1     0     1
     1     0     1     1
     1     0     0     1
     0     0     1     1
     1     0     0     0
     1     0     1     1
M(:,:,2) =
     0     1     0     1
     1     1     0     0
     1     1     0     0
     0     0     1     1
     0     0     0     1
     0     0     1     0
Mout(:,:,1) =
     1     1     0     1
     1     0     1     1
     1     0     0     1
     0     0     3     3
     1     0     0     0
     1     0     1     1
Mout(:,:,2) =
     0     2     0     2
     1     1     0     0
     1     1     0     0
     0     0     3     3
     0     0     0     4
     0     0     3     0