带多个条件的值 [英] Assign values w/ multiple conditions
本文介绍了带多个条件的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我们有一个M = [10 x 4 x 12]
矩阵.例如,我使用M(:,:,4)
:
Let's have a M = [10 x 4 x 12]
matrix. As example I take the 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.
- 如果我在前三列中有0个,但在第四列中有1个,那么这个应该是四个.
- If I have 1 in the first column then all the subsequent 1's should be 1.
- If I have 0 in the first column but 1 in the second, all the subsequent 1's should be 2.
- If I have 0 in the first and second column but 1 in the third then all the subsequent 1's should be 3.
- If I have 0 in the first 3 columns but 1 in the forth then this one should be four.
注意:逻辑矩阵M
的构造如下:
Note: The logical matrix M
is constructed:
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));
推荐答案
这是一种非常简单的方法,适用于2D和3D矩阵.
This is a very simple approach that works for both 2D and 3D matrices.
%// 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);
这篇关于带多个条件的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文