1

I had to construct hemisphere in MATLAB ,so I did this:

figure  
k = 5;
n = 2^k-1;
theta = pi*(-n:2:n)/n;
phi = (pi/2)*(0:2:n)'/n;
X = cos(phi)*cos(theta);
Y = cos(phi)*sin(theta);
Z = sin(phi)*ones(size(theta));  

surf(X,Y,Z);

enter image description here

The code was not written by me so I want to understand this,when I replace ' in
phi = (pi/2)*(0:2:n)'/n;
I get following error :
operator *: nonconformant arguments (op1 is 1x16, op2 is 1x32)

Please explain why is it essential....
Also,I wanted to write an easier code for sketching hemisphere.any idea for some shorter command/method I can use in matlab....

1 Answer 1

2

The '-sign is the transpose. If you matrix-multiply a 16-by-1 array by a 1-by-32, you end up with a 16-by-32 array, where element (i,j) is the ith-element of the first array multiplied with the jth element of the second array. If you omit the transpose, you're trying to matrix-multiply a 1-by-16 array with an 1-by-32 array, which is undefined in linear algebra. Using linear algebra like this is one way to create grids of numbers in Matlab.

An alternative approach is to create the grids via ndgrid, for example:

[theta,phi] = ndgrid(pi*(-n:2:n)/n, (pi/2)*(0:2:n)/n);
X = cos(phi).*cos(theta); 
...

Note that I used the element-wise multiplication .*, since I'm not doing linear algebra here.

To your second question: If the code you posted is too long, the easiest is to put it into a function, so that you can create the plot via a one-line function call.

2
  • @coool: You're welcome. I should have asked first: do you know linear algebra?
    – Jonas
    Oct 8, 2014 at 14:54
  • @WantTobeAbstract: glad you do, b/c otherwise, my explanation would not have made a lot of sense to you :)
    – Jonas
    Oct 8, 2014 at 15:51

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.