Multidimensional array indexing question
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Jason Nicholson
el 8 de Ag. de 2016
Editada: Jason Nicholson
el 9 de Ag. de 2016
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);
Respuesta aceptada
Stephen23
el 8 de Ag. de 2016
Editada: Stephen23
el 8 de Ag. de 2016
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 comentarios
Stephen23
el 8 de Ag. de 2016
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
Más respuestas (1)
Fangjun Jiang
el 8 de Ag. de 2016
x=rand(6,2,4);
MeanX=mean(x,2);
idx=x(:,1,:) < x(:,2,:);
x(idx)=MeanX(idx);
3 comentarios
Fangjun Jiang
el 8 de Ag. de 2016
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);
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!