Doug’s MATLAB Video Tutorials
December 9th, 2008
Video tutorial: 3d indexing
The MATLAB user has this:
clear
clc
M(:,:,1) = [1,2;3,4];
M(:,:,2) = [21,22;23,24];
J = [1,2; 2,1];
They want this:
ans =
[1 22
23 4]
They tried this:
D = M(:,:,J) % This doesn't work,
This video discusses this solution:
[nR, nC] = size(J);
D = zeros(nR,nC);
for r = 1:nR
for c = 1:nC
D(r,c) = M(r,c,J(r,c));
end
end
19:07 UTC |
Posted in Format: Video, Level: Basic |
Permalink |
You can follow any responses to this entry through the RSS 2.0 feed.
You can skip to the end and leave a response. Pinging is currently not allowed.
Leave a Reply
|
What about the following:
[nR,nC] = size(J);
[r,c] = ndgrid(1:nR,1:nC);
M(sub2ind(size(M),r,c,J))
Admittedly it’s harder to read, but it might be faster if J is large.
Martin,
Yes, in MATLAB there are often many ways of doing the same thing. I do not know which one is faster, I suspect that the difference is negligible.
As you said, your code is harder to read, so that would make me want to do it another way. Personally, I try to write code that is easy to read and understand. Once it is working, then if there are sections that are slow, I will try more advanced maneuvers like you pointed out to trade readability for speed.
As always, thanks for reading and adding,
Doug
I am have problem populating 3D matrix using mex file. I have a 3D int array
double *outArray;
dims[0]=4;dims[1]=2;dims[2]=3;
plhs[0]=mxCreateNumericArray(3,dims,mxINT16_CLASS,mxREAL);
outArray = mxGetPr(plhs[0]);
outArray[0]=12;
It gives random numbers in the output. If i do it using 2D matrix I have no problem.. any ideas?
Found the error..should be
plhs[0]=mxCreateNumericArray(3,dims,mxDOUBLE_CLASS,mxREAL);
instead of
plhs[0]=mxCreateNumericArray(3,dims,mxINT16_CLASS,mxREAL);