Maxk gives an incorrect result

1 次查看(过去 30 天)
Kk
Kk 2022-4-22
评论: Voss 2022-4-23
Hi all,
I am trying to get 4 different value from a matrix. I am using maxk to find these values indices. Maxk can find first two maximum value with indices but when I try to find third it gives an incorrect result. for example when ı select row "1" it found 2 maximum value with their column in matrix and gives me 7-15 then I select 7 for my row it should needs to give me 8th column but it gives 1. I cannot understand why
Here is my code:
for i = nodes
if i == 1 [~,seed] = maxk(m(1:n),2);
end
end
s1 = seed(1,1);
s2 = seed(1,2);
for i = nodes
if i == 7 [~,seed2] = maxk(m(7,n),1);
end
end

采纳的回答

Voss
Voss 2022-4-22
For the case that i == 1 you have:
maxk(m(1:n),2)
m(1:n)is the first n elements of m (going in column-major order, which is what MATLAB uses). For example:
m = magic(4)
m = 4×4
16 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1
n = 6;
m(1:n)
ans = 1×6
16 5 9 4 2 11
For the case that i == 7, you have:
maxk(m(7,n),2)
m(7,n) is the element(s) of m at row 7, column(s) n. If n is a scalar, that's one element. For example:
m = magic(7)
m = 7×7
30 39 48 1 10 19 28 38 47 7 9 18 27 29 46 6 8 17 26 35 37 5 14 16 25 34 36 45 13 15 24 33 42 44 4 21 23 32 41 43 3 12 22 31 40 49 2 11 20
n = 6;
m(7,n)
ans = 11
If you want to use maxk on rows of m, then the syntax would be:
maxk(m(1,:),2) % using first row of m
maxk(m(7,:),2) % using 7th row of m
For example (using m as the 7x7 magic square still):
m(1,:)
ans = 1×7
30 39 48 1 10 19 28
m(7,:)
ans = 1×7
22 31 40 49 2 11 20
[~,seed] = maxk(m(1,:),2)
seed = 1×2
3 2
[~,seed2] = maxk(m(7,:),2)
seed2 = 1×2
4 3
  6 个评论
Kk
Kk 2022-4-23
That is exactly the same thing what I was trying to say and do. Thank you very much mate.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by