ploting a 2D matrix and adjusting axes

조회 수: 8 (최근 30일)
Sohaib Bin Altaf
Sohaib Bin Altaf 2018년 7월 7일
답변: Sohaib Bin Altaf 2018년 7월 10일
Hello, I have the following code:
M = zeros(50)
for x = [20,30]
M(x,:) = 1
end
for y = [13,25,37]
for x = [1:20, 30:50]
M(x,y) = 1
end
end
imagesc(M)
when i get the plot, i see the y-axis is in reverse order i-e starting from 50 at the bottom. In my overall simulation this affects my results. You can see the attached picture .Figure 1 is what i want and figure 2 is what this code gives me. I need to know how can i get.

채택된 답변

Sohaib Bin Altaf
Sohaib Bin Altaf 2018년 7월 10일
This thing worked for me:
clc
clear all
close all
M = zeros(50);
% draw lines
for y = [20,30]
M(:,y) = 1;
end
for x = [13,25,37]
for y = [1:20, 30:50]
M(x,y) = 1;
end
end
p1 = [12,48];
p2 = [39,5];
% get direction
d = p1-p2;
d = d/max(abs(d)); % limit to 1 px step size
steps = 0:1:max(abs(p2-p1));
for i=length(p1):-1:1
p_line(:,i) = round(p2(i) + steps.*d(i));
end
idx = sub2ind(size(M), p_line(:,1), p_line(:,2));
walls = sum(M(idx));
M(idx) = 2;
M = flipud(M)
M = rot90(M,-1)
imagesc(M)
set(gca,'YDir','normal')
set(gca,'XDir','normal')
fprintf('You passed %i walls', walls)

추가 답변 (1개)

dpb
dpb 2018년 7월 7일
편집: dpb 2018년 7월 8일
hAx=gca; % handle to the axes
hAx.YDir='normal'; % set Y axis direction--imagesc uses 'reverse' Y
See link to Axes Properties at
doc axes
or the higher level info under Graphics/Formatting and Annotation/Axes Appearance
ADDENDUM
xlim([0 50]), ylim([0 50])
to get the 0 origin to show, maybe??? Your array is 1,50 each direction which are the coordinates imagesc uses; by default it pads a fraction on either direction.
Without more explanation of just what it is you're really after, we're just guessing what the actual problem you perceive is...
  댓글 수: 8
dpb
dpb 2018년 7월 9일
편집: dpb 2018년 7월 9일
That's the documented behavior of imagesc -- from the doc:
"imagesc(C) displays the data in array C as an image ... Each element of C specifies the color for 1 pixel of the image. The resulting image is an m-by-n grid of pixels where m is the number of columns and n is the number of rows in C. The row and column indices of the elements determine the centers of the corresponding pixels."
To use imagesc in Cartesian coordinates with the origin at lower left you need to transpose the C array as well as set the Y-axis 'YDir' property to 'normal'.
I don't know the basis for this convention, specifically.
Sohaib Bin Altaf
Sohaib Bin Altaf 2018년 7월 10일
thanks a lot for your time. I appreciate it.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Images에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by