Build a matrix of zeros with the size of the initial matrix according to indices

조회 수: 3 (최근 30일)
Hi,
I have an initial matrix M(466,504) where I extracted the 30 highest values in each row with the command:
[val,idx] = maxk(M,30,2)
I would like to get now a matrix of zeros of same size but with those 30 values at their initial position.
How could I build such a matrix ?
  댓글 수: 2
Stephen23
Stephen23 2019년 1월 8일
You would need:
  1. the 30 highest values,
  2. their indices,
  3. the size of the original matrix.
Do you have that information?
JohnB
JohnB 2019년 1월 9일
I think your answer was also right !
I kept it in my mail session ;)
Thanks for your help Too !

댓글을 달려면 로그인하십시오.

채택된 답변

Guillaume
Guillaume 2019년 1월 8일
newM = zeros(size(M));
newM(sub2ind(size(M), repmat((1:size(idx, 1))', 1, size(idx, 2)), idx)) = val
  댓글 수: 3
Guillaume
Guillaume 2019년 1월 9일
"It doesn't give the right dimensions"
Could you be a bit clearer about the problem you're having? "the right dimensions" of what? The code I've provided does exactly what you asked: e.g. with the 3 highest values of each row:
>> M = magic(10)
M =
92 99 1 8 15 67 74 51 58 40
98 80 7 14 16 73 55 57 64 41
4 81 88 20 22 54 56 63 70 47
85 87 19 21 3 60 62 69 71 28
86 93 25 2 9 61 68 75 52 34
17 24 76 83 90 42 49 26 33 65
23 5 82 89 91 48 30 32 39 66
79 6 13 95 97 29 31 38 45 72
10 12 94 96 78 35 37 44 46 53
11 18 100 77 84 36 43 50 27 59
>> [val, idx] = maxk(M, 3, 2);
>> newM = zeros(size(M));
newM(sub2ind(size(M), repmat((1:size(idx, 1))', 1, size(idx, 2)), idx)) = val
newM =
92 99 0 0 0 0 74 0 0 0
98 80 0 0 0 73 0 0 0 0
0 81 88 0 0 0 0 0 70 0
85 87 0 0 0 0 0 0 71 0
86 93 0 0 0 0 0 75 0 0
0 0 76 83 90 0 0 0 0 0
0 0 82 89 91 0 0 0 0 0
79 0 0 95 97 0 0 0 0 0
0 0 94 96 78 0 0 0 0 0
0 0 100 77 84 0 0 0 0 0
As you can see you get the highest 3 values of each row in exactly the same position as they were originally, in a matrix the same size as the original one.
JohnB
JohnB 2019년 1월 9일
Today it is working x) Yesterday It doesn't ... Maybe I missed some characters by myself :S
Anyway Huge Regards !

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by