- the 30 highest values,
- their indices,
- the size of the original matrix.
Build a matrix of zeros with the size of the initial matrix according to indices
1 view (last 30 days)
Show older comments
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
on 8 Jan 2019
You would need:
Do you have that information?
Accepted Answer
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
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.
More Answers (0)
See Also
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!