I have a matrix x that is of size [61 2 45].
linearIndex = find(x(:,1,:) < x(:,2,:));
xAverage = (x(:,1,:) + x(:,2,:))/2;
Now I want to assign the average to anywhere x(:,1,:) < x(:,2,:). I come up with the following but it seems a bit verbose and un-elegant. Thoughts on how to do this better?
[subScriptIndex1, subScriptIndex2, subScriptIndex3] = ind2sub(size(linearIndex), linearIndex);
x(subScriptIndex1, 1, subScriptIndex3) = xAverage(subScriptIndex1, 1, subScriptIndex3);
x(subScriptIndex1, 2, subScriptIndex3) = xAverage(subScriptIndex1, 1, subScriptIndex3);

댓글 수: 1

The new code looks like this:
linearIndex = linearIndex(:,[1,1],:);
x(linearIndex) = xAverage(linearIndex);
This is cleaner.

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

 채택된 답변

Stephen23
Stephen23 2016년 8월 8일
편집: Stephen23 2016년 8월 8일

0 개 추천

Your understanding is correct: if a logical index is shorter than the array it is being used on, then the index is not expanded in any way. The solution is to make the index the exact size that you require:
x = reshape((1:18)',[3 2 3])
xx = x;
idx = x(:,1,:) < x(:,2,:);
idx = idx(:,[1,1],:) % or repmat
x(idx) = nan
[xx(:) x(:)]

댓글 수: 3

Excellent. That works!
Note that this behavior is closely related:
>> X = [1,2,3,4];
>> X([false,true]) % shorter than X
ans =
2
>> X([false,true,false(1,200)]) % longer than X, but only false..
ans =
2
Interesting.

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

추가 답변 (1개)

Fangjun Jiang
Fangjun Jiang 2016년 8월 8일

1 개 추천

x=rand(6,2,4);
MeanX=mean(x,2);
idx=x(:,1,:) < x(:,2,:);
x(idx)=MeanX(idx);

댓글 수: 3

The meanX line is better than what I did for sure.
The line starting with x(idx) doesn't work though. You don't get an error but it is wrong. The problem is the size of idx is [6 1 4] while x is of size [6 2 4]. I think what is happening is logical indexing relies on the linear index of an array. Therefore size of idx has 24 elements while x has 48 elements. Only the first 24 elements of x are modified while the 2nd 24 elements are not modified. Try the following to see what I am saying. Note that the 2nd half according to the linear index of x is not modified. The [xx(:) x(:)] when output to the command window, should make this clear.
x = reshape((1:18)',[3 2 3])
xx = x;
idx = x(:,1,:) < x(:,2,:);
x(idx) = nan
[xx(:) x(:)]
How about this? I think it works but what if the second dimension is larger than 2? There must be a a better way.
x=rand(6,2,4);
MeanX=mean(x,2);
MeanX(:,2,:)=MeanX(:,1,:);
idx=x(:,1,:) < x(:,2,:);
idx(:,2,:)=idx(:,1,:);
x(idx)=MeanX(idx);
Jason Nicholson
Jason Nicholson 2016년 8월 9일
편집: Jason Nicholson 2016년 8월 9일
Your second suggestion does work.
When the dimension is greater than 2, I think repmat may be the solution.

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

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

질문:

2016년 8월 8일

편집:

2016년 8월 9일

Community Treasure Hunt

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

Start Hunting!

Translated by