MATLAB Answers

How to add the value of the 3 highest elements automatically from a vector?

4 ビュー (過去 30 日間)
Eddy Iswardi
Eddy Iswardi 2020 年 3 月 28 日
コメント済み: Peng Li 2020 年 3 月 28 日
I want to add the 3 highest elements of 'y' to 'sk'. But I don't know what code to use to automatically add them. in this case, the elements in question are 12, 12, and 13. So that the value will be 12 + 9 = 21, 12 + 9 = 21, 13 + 9 = 22. This is my code
clc;
clear all;
x1=[1 2 3 4 5 6 7 8 9 10 11];
x2=[1 2 3 4 5 6 7 8 9 10 11];
y=[10 9 11 10 11 11 9 10 12 12 13];
sx=9;
and the result will be
y = [10 9 11 10 11 11 9 10 21 21 22]

  0 件のコメント

Sign in to comment.

回答 (3 件)

Peng Li
Peng Li 2020 年 3 月 28 日
[~, ind] = sort(y);
y(ind(end-2, end)) = y(ind(ind-2, end)) + ax;
Should meet your need.

  4 件のコメント

表示 1 件の古いコメント
Ameer Hamza
Ameer Hamza 2020 年 3 月 28 日
There is a few typos in Peng's code. try it like this
[~, ind] = sort(y);
y(ind(end-2:end)) = y(ind(end-2:end)) + sx;
or like this with a bit simple indexing
[~, ind] = sort(y, 'descend');
y(ind(1:3)) = y(ind(1:3)) + sx;
Eddy Iswardi
Eddy Iswardi 2020 年 3 月 28 日
oke, thank you. It's work now.
Peng Li
Peng Li 2020 年 3 月 28 日
Thanks Ameer. Using cell phone lol

Sign in to comment.


J. Alex Lee
J. Alex Lee 2020 年 3 月 28 日
like this?
[~,idx] = maxk(y,3)
y(idx) = y(idx) + sx
Are x1 and x2 irrelevant to your question?

  1 件のコメント

Eddy Iswardi
Eddy Iswardi 2020 年 3 月 28 日
I get an error at 'maxk'
Undefined function or variable 'maxk'.
I use matlab 2016a

Sign in to comment.


Torsten
Torsten 2020 年 3 月 28 日
[~,idx]=maxk(y,3);
y(idx)=y(idx)+sx;
y

  3 件のコメント

Eddy Iswardi
Eddy Iswardi 2020 年 3 月 28 日
I get an error at 'maxk'
Undefined function or variable 'maxk'.
I use matlab 2016a
Torsten
Torsten 2020 年 3 月 28 日
[~,idx] = sort(y,'descend');
y(idx(1:3))=y(idx(1:3))+sx;
y
Eddy Iswardi
Eddy Iswardi 2020 年 3 月 28 日
oke, thank you. It's work now.

Sign in to comment.


Translated by