Further simplify a simple vectorized operation
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Christopher
el 9 de Mzo. de 2014
Comentada: the cyclist
el 9 de Mzo. de 2014
I have a row vector of values 'gridx'. For example:
gridx=[0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5]
I also have a large column vector of values P, which are to act as indices for the vector gridx.
Thus, I can sample P(:,1) and get the corresponding values fro gridx as:
P(:,2) = gridx(P(:,1));
I want to use these values to perform another operation, so I replace it with the result as:
P(:,2)=MX-P(:2);
where MX is a column vector of length P(:,1)).
This works, but I want to shorten the code as:
P(:,2)=MX-gridx(P(:,1));
Unfortunately, this does not work. What is wrong with my syntax?
0 comentarios
Respuesta aceptada
the cyclist
el 9 de Mzo. de 2014
Editada: the cyclist
el 9 de Mzo. de 2014
The crux of the issue is that
gridx(P(:,1))
is a row vector (because P is a row vector).
In some cases, like simple assignment statements, MATLAB will allow some wiggle room and transpose the right-hand side of the assignment for you (if the lengths of the vectors match). For example, the following will work:
A = magic(3)
A(:,2) = [1 2 3]
In other cases, like vector math operations, MATLAB is more stringent, requiring an exact match in dimensions as well as length. So, for example, the following gives the same error as you see in your example:
B = [1 2] - [1 2]'
One simple solution in your case is to define gridx as the transpose of how you did it:
gridx=[0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5]'
Then it should work fine.
4 comentarios
the cyclist
el 9 de Mzo. de 2014
I think you might be missing the bigger picture. Would you expect this operation to work?
A = rand(1,2) - rand(2,1)
?
I would not, because the dimensions don't match (even though the lengths do). That is exactly what your code was trying to do. Your MX was a column vector, and your gridx was a row vector. My version corrected that mismatch.
Now, as I said, sometimes MATLAB will be a little less stringent, and "guess" what you meant. But, it can't always do that for you. Sometimes (most of the time!) you need to get the dimensions matched yourself. That is not a "syntactic oversight".
Más respuestas (1)
Ver también
Categorías
Más información sobre Resizing and Reshaping Matrices 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!