Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eliminating for loops in Matlab

Here's a simple question. The following nested for loop creates an array of sine-wave values.

N = 2^16;
for m = 1:10;
    for i = 1:N
        sine(m,i) = sin(2*pi*i./(8*2^m));
    end
end

It seems like I should be able to create this array without the use of the for loops, but I've tried various syntaxes and always get an error message. Thanks in advance for any insights.

like image 363
MatlabDog Avatar asked Dec 06 '22 00:12

MatlabDog


2 Answers

You could use bsxfun like this:

sine = sin(bsxfun(@times, 2*pi*(1:2^16), 1./(8*2.^(1:10))' ));
like image 108
MeMyselfAndI Avatar answered Jan 11 '23 13:01

MeMyselfAndI


Try the following:

ii = 1:2^16;
m  = [1./(2.^(1:10))].'% transpose

prefactor = 2 * pi / 8;

sine = sin(prefactor * m * ii);

I perform a matrix multiplication A*B, in which a is a column vector size nrows, and B is a row vector size ncols, the resulting matrix will be of size nrows x ncols. Therefore m is a column vector and ii a row vector.

like image 31
Nick Avatar answered Jan 11 '23 14:01

Nick