0

I'm trying to figure out a way to make a plot of a function in Matlab that accepts k parameters and returns a 3D point. Currently I've got this working for two variables m and n. How can I expand this process to any number of parameters?

K = zeros(360*360, number);
for m = 0:5:359
    for n = 1:5:360
            K(m*360 + n, 1) = cosd(m)+cosd(m+n);
            K(m*360 + n, 2) = sind(m)+sind(m+n);
            K(m*360 + n, 3) = cosd(m)+sind(m+n);
    end
end
K(all(K==0,2),:)=[];

plot3(K(:,1),K(:,2),K(:,3),'.');
end

The code you see above is for a similar problem but not exactly the same.

1 Answer 1

2

Most of the time you can do this in a vectorized manner by using ndgrid.

[M, N] = ndgrid(0:5:359, 1:5:360);

X = cosd(M)+cosd(M+N);
Y = sind(M)+sind(M+N);
Z = cosd(M)+sind(M+N);

allZero = (X==0)&(Y==0)&(Z==0); % This ...
X(allZero) = [];                % does not ...
Y(allZero) = [];                % do ...
Z(allZero) = [];                % anything.

plot3(X,Y,Z,'b.');

A little explanation: The call [M, N] = ndgrid(0:5:359, 1:5:360); generates all combinations, where M is an element of 0:5:359 and N is an element of 1:5:360. This will be in the form of two matrices M and N. If you want you can reshape these matrices to vectors by using M = M(:); N = N(:);, but this isn't needed here. If you were to have yet another variable, you would use: [M, N, P] = ndgrid(0:5:359, 1:5:360, 10:5:1000).

By the way: The code part where you delete the entry [0,0,0] doesn't do anything here, because this value doesn't appear. I see you only needed it, because you were allocating a lot more memory than you actually needed. Here are two versions of your original code, that are not as good as the ndgrid version, but preferable to your original one:

m = 0:5:359;
n = 1:5:360;
K = zeros(length(m)*length(n), 3);
for i = 1:length(m)
    for j = 1:length(n)
            nextRow = (i-1)*length(n) + j;
            K(nextRow, 1) = cosd(m(i)) + cosd(m(i)+n(j));
            K(nextRow, 2) = sind(m(i)) + sind(m(i)+n(j));
            K(nextRow, 3) = cosd(m(i)) + sind(m(i)+n(j));
    end
end

Or simpler, but a bit slower:

K = [];
for m = 0:5:359
    for n = 1:5:360
            K(end+1,1:3) = 0;
            K(end, 1) = cosd(m)+cosd(m+n);
            K(end, 2) = sind(m)+sind(m+n);
            K(end, 3) = cosd(m)+sind(m+n);
    end
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.