How to write smart coding ?
2 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
Stephen23
2015-7-8
编辑:Stephen23
2015-7-8
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!