How do I create this matrix in Matlab?
I'm attempting to solve the Code Golf: Build Me an Arc problem. My solution's not bad, but开发者_Python百科 I figure, there's a simpler way to do it. Does anybody know how to generate an nxn
matrix like this, given n
? I spent 57 characters getting it!
3 0 0 0 2 0 0 0 1
0 3 0 0 2 0 0 1 0
0 0 3 0 2 0 1 0 0
0 0 0 3 2 1 0 0 0
4 4 4 4 8 8 8 8 8
0 0 0 5 6 7 0 0 0
0 0 5 0 6 0 7 0 0
0 5 0 0 6 0 0 7 0
5 0 0 0 6 0 0 0 7
I would like to beat some of these matrices into shape.
Update:
This is how I get it now.
%%# Create the grid
[X Y]=meshgrid(-r:r);
%%# Compute the angles in degrees
T=atan2(-Y,X)/pi*180;
%%# Get all the angles
T=T+(T<=0)*360;
As you can see, I don't need most of the entries in T
.
Since this is related to a Code Golf question, consider:
[X Y]=meshgrid(r:-1:-r,-r:r);
T=180+atan2(Y,X)*180/pi;
which would save you 3 characters...
Listed in this posted is a one-liner solution code with bsxfun
that saves us from using temporary variables as it internally does the expansion
that meshgrid
does explicitly and at the sametime give us the ability to mention a mathematical operation to be performed between the two inputs listed inside bsxfun
. With these internal operations, a bsxfun
based solution seems perfect for such a code-golf thing with 43 characters
solution for the stated problem -
T=180+bsxfun(@atan2,[-r:r]',r:-1:-r)*180/pi
精彩评论