필터 지우기
필터 지우기

How to do indexing without moving to a new variable ?

조회 수: 12 (최근 30일)
Karthik KJ
Karthik KJ 2012년 10월 27일
Hi,
I have an variable x=[1 2 3 4 5]
I need to find the mean of the worst half ie, (3+4+5)/2. For that I am sorting x
sort(x,'descend') ----> [5 4 3 2 1]
I need to find the mean of the first 3 numbers with only single statement
mean(sort(x,'descend')(1:3,1)) - This is not working, getting the following error
??? Error: ()-indexing must appear last in an index expression.
Appreciate the help
Karthik

답변 (6개)

Matt Fig
Matt Fig 2012년 10월 27일
As far as memory goes, if you are o.k. in making the temporary variable through the other methods suggested here then you are o.k. making the temporary variable and overwriting it immediately. This is how I approach the problem when I don't want memory filled with a bunch of non-useful variables. There is no real advantage memory-wise in doing it in one line, and there may even be a penalty if one is forced to create several intermediate structures like padded arrays or cell arrays.
clear
A = randi(bitmax,1,1e6);
M = sort(A,'descend'); % This will die immediately below.
M = mean(M(1:3)) % your workspace is 'clean' again!

Azzi Abdelmalek
Azzi Abdelmalek 2012년 10월 27일
sum(sort(x,'descend').*[ones(1,3) zeros(1,2)])/3
  댓글 수: 1
Azzi Abdelmalek
Azzi Abdelmalek 2012년 10월 27일
or using cellfun
cellfun(@(x) mean(x(1:3)),{sort(x,'descend')},'un',0)

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


Star Strider
Star Strider 2012년 10월 27일
My contribution:
mx = max(mean(reshape([sort(x,'descend') 0],3,2)).*[1 0]);

per isakson
per isakson 2012년 10월 27일
AFAIK: It is not possible. Why do you need a single statement?
  댓글 수: 3
Karthik KJ
Karthik KJ 2012년 10월 27일
Ok. The matrix is too large that I thought not to make a temp variable in between.
Walter Roberson
Walter Roberson 2012년 10월 27일
The array that is produced from the sort() occupies the same amount of memory whether it is passed on or given a name, except for a small number of bytes in the name table. The data block produced in the expression is internally pointed to both ways; when you assign an expression, a copy of the data is not made if instead the data block can be internally pointed to.

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


Matt J
Matt J 2012년 10월 27일
A slightly more exotic solution using this class
result = mean(flib.S.sort{x,'descend'}(1:3));
Although, I guess if you were allowed to use additional mfiles, there are much more trivial ways...

Chris A
Chris A 2012년 10월 27일
Does this work?
m = [5 4 3 2 7 1 6 8 9 10];
sum(sort(m)'.*vertcat(ones(numel(m)-numel(m)/2,1),zeros(numel(m)/2,1))),
It does create another matrix,but it is a single line of code.
Chris
  댓글 수: 1
Matt J
Matt J 2012년 10월 28일
It works, but it is the same as Azzi's solution, given earlier.

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

카테고리

Help CenterFile Exchange에서 Cell Arrays에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by