Monday 15 August 2011

Making Matlab Code more robust by taking out some for loops (2D Discrete Fourier Transform) -


Here is my code for the 2D Discrete Fourier Transform. I know, this is a bit brutal force, but before taking this semester before mathematical physics, I did not have much programming experience.

I am wondering why my program is so slow, and if there is something that goes out of it, it will be made stronger [it takes a very long time, and I hope someone More experienced than I can see some wrong].

  function [trance] = D2 fractures (matrix) [O, p] = size (matrix); F = 0; U = 0: 1: p-1 S = Xi + 1 for U = 0: 1: p-1 for U = 0: 1: Xi = 0: 1: o-1; T = Yi + 1; C = matrix (s, t) * xp (-1i * 2 * pi * (u * xi / o + v * yi / p)); F = F + C; End and C = V + 1; Ti = U + 1; G (she, c) = F; F = 0; End end trans = g;  

I'm sorry to be lazy, but I'll give you a tip. That's what's going on here. See, many beginners start using loops for everything, even while working some element on the vector. Example:

 % Assume that we want to square each element inside the random vector. % First we make a vector vector = rand (10,1); % So we loop on each element, this square and store it where it was. I = 1 for: vector.length () vector (i) = vector (i) ^ 2; End  

Now it's a simple, better and fast solution:

  vector = rand (10,1); % Pointwise actions in Matlab are indicated with dot (.) Vector = vector. ^ 2;  

So you always want to think about how you can do the operation in one stage instead of writing for the loop. You have to check your problem for yourself and see how you can apply this application. The following elements in Matlab are absolute functions:

  vec1. Vec2% vec1 and vec2 elements together at vec1 / Vec2% element-wise split vec1 + vec2% add element is basically element-wise by vec1 - vec2% same vec. ^ 2% of the square vec% element is not the same thing% Vec ^ 2!  

No comments:

Post a Comment