Clear Filters
Clear Filters

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

1 view (last 30 days)
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 Comments
Stephen23
Stephen23 on 8 Jan 2019
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 on 9 Jan 2019
I think your answer was also right !
I kept it in my mail session ;)
Thanks for your help Too !

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 8 Jan 2019
newM = zeros(size(M));
newM(sub2ind(size(M), repmat((1:size(idx, 1))', 1, size(idx, 2)), idx)) = val
  3 Comments
Guillaume
Guillaume on 9 Jan 2019
"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 on 9 Jan 2019
Today it is working x) Yesterday It doesn't ... Maybe I missed some characters by myself :S
Anyway Huge Regards !

Sign in to comment.

More Answers (0)

Categories

Find more on Multidimensional Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!