A = [0,0,1,0,1,0,1,0,0,0;
0,0,0,0,1,0,1,0,0,0;
0,0,1,0,1,0,1,0,0,0];
B = [2,5;
1,6;
3,10];预期输出单元阵列:
C = [1,1,1,1; %// 2-3-4, 3-4-5, 4-5, 5
0,0,1,1,1,0; %// 1-2-3, 2-3-4, 3-4-5, 4-5-6, 5-6, 6
1,1,1,1,1,0,0,0]; %// 3-4-5, 4-5-6, 5-6-7, 7-8-9, 8-9-10, 9-10, 10矩阵B包括在矩阵A上应使用哪些列来执行条件。例如,B的第一行是2和5;因此,应该使用矩阵A第2第5列之间的元素来执行条件。B的第二行是1和6;因此,应该使用第1第6列之间的元素来执行条件。等等..。
条件:如果连续3个元素的和大于或等于1,则将1写入矩阵C,否则写入0。例如,A包含三个连续元素(和为0+1+0=1),因此将1写入矩阵C。另一个例子是,第二行中A的前三个元素为0,0(和为0),因此将0写入矩阵C,等等。
“有时它只能被认为是一个或两个连续的元素”。
例如,A的第一行的条件执行以第5列结束,因此只应考虑值5列;即1.SO1写入矩阵C。
解释C:的第一行
1,由于( A(1,:)的2,3,4元素之和) >= 1 1,由于( A(1,:)的3,4,5元之和A(1,:)) >= 1的最大值为5,这里只取2个连续元素 1,由于(仅A(1,:)) >= 1的4,5元素之和最大极限为5,这里只取1个连续元素 1,自( A(1,:)的第5元素之和) >= 1
没有for循环,只有矩阵操作,我如何才能完成这个复杂的任务?或者有什么诡计?
发布于 2015-05-19 04:08:24
使用mat2cell、cellfun、im2col和any
subMatLen = 3;
%// Converting both A & B matrix to Cell Arrays to perform operations Row-wise
AC = mat2cell(A,ones(1,size(A,1)),size(A,2));
BC = mat2cell(B,ones(1,size(B,1)),size(B,2));
%// Getting only the columns of each rows within the limits specified by Matrix B
%// Also appended with zeros for my own convenience as it wont affect the 'summing' process
out = cellfun(@(x,y) [x(y(1):y(2)),zeros(1,subMatLen-1)],AC, BC, 'uni', 0);
%// Finally taking each 1x3 sliding sub-matrix and returning 1 if `any` of it is non-zero
%// which is equivalent to summing and checking whether they are >= 1
out = cellfun(@(x) any(im2col(x, [1,subMatLen], 'sliding')), out, 'uni', 0);示例输入:
A = [0,0,1,0,1,0,1,0,0,0;
0,0,0,0,1,0,1,0,0,0;
0,0,1,0,1,0,1,0,0,0];
B = [2,5;
1,6;
3,10];输出:
>> celldisp(out)
out{1} =
1 1 1 1
out{2} =
0 0 1 1 1 0
out{3} =
1 1 1 1 1 0 0 0如果要将它们作为单个行或列矩阵,可以将其添加到代码的底部:
out = cat(2,out{:})或
out = (cat(2,out{:})).'https://stackoverflow.com/questions/30313448
复制相似问题