tags:

views:

65

answers:

2

The x-axis and y-axis are interchanged in the figure by running the following matlab function I wrote.

Could anyone tell me where the problem is or help me fix it? Thanks in advance for any help.

function axislabeling(n)
x=1:1:n;
y=1:1:n;

z=zeros(n,n);

for i=1:n
    for j=1:n
        z(i,j)=i;
    end
end
surf(x,y,z(x,y))

xlabel('x-axis')
ylabel('y-axis')
zlabel('z-axis')
A: 

I suspect the problem is not that the axes are mislabelled but that the graph is not what you expect. The reason is that matlab matrices are accessed (row, column) -- ie, (y,x) -- rather than (x,y) as you have it. So when you're setting z(i,j)=i you're getting the slope in the wrong direction.

walkytalky
walkytalky, so how to fix the problem in my codes? Thanks.
@user376089: I don't think you understand what walkytalky is saying. The axes ARE labelled correctly - there's nothing wrong with them. Take a look and check - the z axis is obviously correct. Therefore, if your axes are to be a right-handed coordinate system, they have to be defined how MATLAB plots/labels them. If you wanted to plot a different function, then define the function differently.
Doresoom
@user376089 In this specific case you can trivially change the code to `z(i,j)=j`. In general you need to get a better grip on what's where in your matrices. (I'm not being intentionally dismissive -- nearly every Matlab user know has had a problem like this at some point.)
walkytalky
+1  A: 

I agree with @walkytalky on this one.

For troubleshooting purposes, it may be better to use a case where x~=y to help you see things more clearly.

For example:

n=10;
x=1:n;  %# stepsize of 1 is default and need not be specified
y=x.^2; %# instead of y=1:n to more easily distinguish x and y
z=repmat(x',1,n) %# use of repmat should be faster than a nested loop
surf(x,y,z)
ylabel('y-axis')   
xlabel('x-axis')   
zlabel('z-axis')

gives a plot where the x and y axes are clearly labelled correctly.

Doresoom
Doresoom, I ran your codes, but got error messages. Do you know how to fix the problem in my codes? Thanks!
Whoops, I accidentally switched n and 1 in the z definition line. Should work now.
Doresoom

related questions