Given an element of a matrix, How to print all the arrays containing that element?
1 次查看(过去 30 天)
显示 更早的评论
Given an element of a matrix, I need to print all the arrays containing that element. So basicaly for each element I need 4 arrays.
Suppose I have the matrix:
A = magic(4)
A =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
If I give input
x = 7
I should get output as:
out1 = 0 9 6 12
out2 = 0 2 11 14
out3 = 0 5 15 0
out4 = 13 10 4 0
Any help will be appreciated. Thank You.
5 个评论
回答(1 个)
Stephen23
2019-3-11
编辑:Stephen23
2019-3-11
This should get you started, adjust as required:
>> A = magic(4)
A =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
>> N = 7;
>> Rv = {[+0,+0,+0,+0],[-3,-2,-1,+1],[-2,-1,+1,+2],[-2,-1,+1,+2]};
>> Cv = {[-2,-1,+1,+2],[+0,+0,+0,+0],[-2,-1,+1,+2],[+2,+1,-1,-2]};
>> B = zeros(size(A)+5);
>> B(4:end-2,4:end-2) = A;
>> [Rx,Cx] = find(B==N);
>> F = @(r,c)reshape(B(sub2ind(size(B),Rx+r,Cx+c)),1,[]);
>> Z = cellfun(F,Rv,Cv,'Uni',0);
>> Z{:}
ans =
0 9 6 12
ans =
0 2 11 14
ans =
0 5 15 0
ans =
13 10 4 0
You can access the data in the cell array using indexing:
You could probably do something similar using blockproc:
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!