How to loop and save values in new matrix

I have the following code which identifies the velocity values at different values of KK.

load('Vq.mat')
KK=1;
ft = fftshift(fft2(Vq));
kx = [-70:1:70];
ky = [-70:1:70];
for i1=1:length(kx)
    for i2=1:length(ky)
        kh(i1,i2)=sqrt(kx(i1).^2+ky(i2).^2);
        if (kh(i1,i2)>KK && kh(i1,i2)<KK+1)

        else
            ft(i1,i2)=0;
        end

    end
end
K=sum(ft);

So, when I set the value of KK as 1 the code will then loop through the matrix kh and find the locations where KK = 1 and grab the velocity at that location (through the if statement). The code then zeros all the other values in the ft matrix and only keeps the velocity values at KK = 1. I then sum these values to create K.

My problem is that I want to loop through KK values from 1:70. So when KK = 2, the code would again loop through kh and identify the velocities at KK = 2. It would then sum these values and then add to the matrix K.

At the end the single matrix of K should include all the sums of the individual values found at different values of KK

https://www.dropbox.com/s/vi6un5jyby7akej/Vq.mat?dl=0 This is the link to the data file.

Upvotes: 1

Views: 162

Answers (1)

AboAmmar
AboAmmar

Reputation: 5559

The following code is greatly simplified. The main idea is that you find the indices (inds) of kh values that are between KK and KK+1 using find builtin function and sum the corresponding ft values at the same indices. You repeat this algorithm for all values of KK and add all the computed sums.

load('Vq.mat')
ft = fftshift(fft2(Vq));
kx = -70:70;
ky = -70:70;
kh = sqrt(kx.^2 + ky.^2.'); % compute kh only once

sumK = 0;       % accumulate sum for each KK
for KK = 1:70   % loop over all kk values
    inds = find(kh > KK & kh < KK+1);
    sumK = sumK + sum(ft(inds));
end
disp(sumK)      % 267.85 - 2.8089e-14i

look how vectorization simplified the code and made it run faster. For example, I created the kh matrix only once outside the loop instead of calculating it 70 times. Also using vectorized builtin functions like find greatly improves the performance and readability of the code vs. if conditions and for loops. This is how idiomatiic MATLAB code should be written for conciseness and speed.

Update: This is the updated answer after comments from OP:

load('Vq.mat')
ft = fftshift(fft2(Vq));
kx = -70:70;
ky = -70:70;
kh = sqrt(kx.^2 + ky.^2.'); % compute kh only once

K = zeros(70,141);    % accumulate sum for each KK
for KK = 1:70         % loop over all kk values
    K(KK,:) = sum( ft .* (kh > KK & kh < KK+1) );
end

This is how K looks at the end (spy(K)):

enter image description here

Upvotes: 2

Related Questions