How to write smart coding ?

6 views (last 30 days)
Jes
Jes on 8 Jul 2015
Commented: Jes on 8 Jul 2015
Applying 3 level of DWT provide me 22 subbands. How do I write efficient coding for calculating the energy of 22 subbands. I have written the following code:-
function [E1,E2,E3,E4,E5,E6,E7,E8,E9,E10,E11,E12,E13,E14,E15,E16,E17,E18,E19,E20,E21,E22]=featener(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v)
[Sx,Sy,Sz]=size(a);
for x=1:Sx
for y=1:Sy
for z=1:Sz
E1=sum(sum(sum(a(x,y,z)*a(x,y,z))));
end
end
end
for loop etc for 22 subbabds. How to avoid these many for loops? Any help is appreciated.

Accepted Answer

Stephen23
Stephen23 on 8 Jul 2015
Edited: Stephen23 on 8 Jul 2015
Don't do this. Putting lots of input and output arguments like that is untidy and buggy programming, and sequentially named variables are a really bad idea. Instead of this:
[E1,E2,E3,E4,E5,E6,E7,E8,E9,E10,E11,E12,E13,E14,E15,E16,E17,E18,E19,E20,E21,E22] = featener(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v)
you should simply do this:
out = featener(inp)
where each of inp and out can be arrays (numeric or cell arrays) containing all of your data. These can then be accessed using proper indexing (which is essentially what the numbers were in the variable names of your code were pretending to be).
Now you do not need 22 loops.
But note that that code does not make much sense anyway: within the loops x, y and z are scalars, so a(x,y,z) is a scalar, and then squaring it will get you another scalar, and it does not matter how many times you sum it will still be the same scalar:
sum(sum(sum(a(x,y,z)*a(x,y,z))));
is the same as
a(x,y,z)^2
when x, y and z are scalars.
You need to think about your algorithm. Or tell us what you are trying to achieve and we can show you how it can be done using some MATLAB code.

More Answers (0)

Categories

Find more on Image Processing Toolbox in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!