0
votes

I'm trying to create a matrix K with a certain function

My code is as follows

K=zeros(360*360,3);
for m = 0:360
    for n = 0:360
        for d=0:5
            U1(1,1)= cos(m)+cos(m+n);
            U1(1,2)= sin(m)+sin(m+n);
            U1(1,3)=-d;
            K(m,n)=(U1);

        end
    end
end

However I keep getting an error, "Subscript indices must either be real positive integers or logicals."

Can somebody explain how this can be fixed?

1
you get the error because m and n start from 0, they should start from 1.Rashid
Hi @Kamtal Subscripted assignment dimension mismatch. is the error I get when I change m and n start from 1.Trippy
@Trippy: That's because of K(m,n)=(U1);. See my answer below.Roney Michael
you also need to do K=zeros([360,360,3]); and K(m,n,:)=U1;Rashid

1 Answers

1
votes

K is a (360^2)x3 matrix here. What you're trying to do seems to be:

K(m*n, :) = U1;

There would also be a problem here since your m & n start from 0, not 1.

I would rather do the following:

K = zeros(360, 360, 3);
for m = 1:360
    for n = 1:360
        for d = 0:5
            K(m, n, 1) = cos(m) + cos(m+n);
            K(m, n, 2) = sin(m) + sin(m+n);
            K(m, n, 3) = -d;
        end
    end
end

This would give you a 360x360x3 3D matrix where m & n directly index into the structure.

EDIT

Based on @Trippy's comment below, the code would need to be modified as follows:

K = zeros(360*360, 3);
for m = 0:359
    for n = 1:360
        for d = 0:5
            K(m*360 + n, 1) = cos(m) + cos(m+n);
            K(m*360 + n, 2) = sin(m) + sin(m+n);
            K(m*360 + n, 3) = -d;
        end
    end
end

This would fill in the matrix K in row-major form, which I'm assuming is what you're looking for.