Writing elegant MATLAB code
6 views (last 30 days)
I have a great interest in writing my MATLAB code the "right" way. I want it to be compact, readable and fast. As such, I have a few patterns that I see occasionally. Some I have found neat solutions to, some I have not.
1. Matrix mixing or tensors? If you want to do image processing, you may want to do linear color transforms. Each output channel should be a weighted sum of each input channel (channels indexed by the third matrix dimension). Now, there are probably neat ways of doing this in image processing toolbaox, but tht is expensive, does not make for portable code, and this pattern could appear in other contexts than image processing. I guess that some tensor/kron() operation would do this cleaner, but I did not figure it out.
rgb = double(imread('ngc6543a.jpg'));
M = [0.1 0.8 0.1; -0.1 1.2 -0.1; 0 0.5 0.5];
rgb2(:,:,1) = M(1,1)*rgb(:,:,1) + M(1,2)*rgb(:,:,2) + M(1,3)*rgb(:,:,3);
rgb2(:,:,2) = M(2,1)*rgb(:,:,1) + M(2,2)*rgb(:,:,2) + M(2,3)*rgb(:,:,3);
rgb2(:,:,3) = M(3,1)*rgb(:,:,1) + M(3,2)*rgb(:,:,2) + M(3,3)*rgb(:,:,3);
2. Indexing I want to make an irregular index into a vector/matrix. For instance, [x1, x2, x11, x12, x21, x22]. Ideally, I'd like to type something like: x(1:(10+1:2):N) Is there a neat pattern for this? Perhaps using ind2sub?
Titus Edelhofer on 22 Jun 2011
for these cases I usually cange from 3D to 2D:
[n,m,~] = size(rgb);
rgb2D = reshape(rgb, n*m, 3);
rgb2D2 = rgb2D * M';
rgb2 = reshape(rgb2D2, n, m, 3);
Andrew Newell on 22 Jun 2011
- To improve on your code, you'll probably need a third-party package like TPROD. EDIT 06/24/11: Another package is MTIMESX.
- One way is
I = [1:10:21; 2:10:22];
A more general approach is the following:
lastDigit = 0:2;
I = 0:99; I = I(ismember(mod(I,10),lastDigit));
Whether it is "neat" will be a matter for personal taste.
Sean de Wolski on 22 Jun 2011
I would do your above operation with:
rgb3 = zeros(size(rgb));
for ii = 1:3
rgb3(:,:,ii) = sum(bsxfun(@times,reshape(M(ii,:),[1 1 3]),rgb),3);
There's probably a way use just one call after reshaping rgb into the 4th dimension but I'm too busy right now to toy with it. Maybe later.
Andrei Bobrov on 22 Jun 2011
1. My variant - is worse than variant of Titus Edelhofer
reshape(sum(bsxfun(@times,reshape(rgb,,3),permute(M,[3 2 1])),2),size(rgb))
2. My variant - is worse than variant of Andrew Newell
ind = cumsum([1:2;10*ones(length(x)/10-1,2)])';