user7408968
user7408968

Reputation:

How to draw differently spaced grid lines in Matlab

On mathworks, I have found a code which is suppossed to draw grid lines in a plot:

g_x = -25:1.25:0;
g_y = -35:2.5:-5;
for i = 1:length(g_x)
    plot([g_x(i) g_x(i)],[g_y(1) g_y(end)],'k:')% y grid lines
    hold on
end
for i=1:length(g_y)
    plot([g_x(1) g_x(end)],[g_y(i) g_y(i)],'k:') % x grid lines
    hold on    
end

here's a link

I don't understand the plot command: e.g. the y grid lines - one of the inputs is a vector containing all the spacing points of the x-axis, where I want to have a grid. These points are given in two columns and they are assigned to the second vector, which only contains the first and the last point shown on the y-axis. As I understand this command, it will for example take the first element g_x(1) and g_y(1) and plot a : , it will then take g_x(2) and g_y(1) and plot :, and so on. But How does it keep on plotting : from g_y(1) continuously until g-y(end) ?

Upvotes: 2

Views: 2459

Answers (2)

Suever
Suever

Reputation: 65430

To directly answer your question, it simply plots the two endpoints of each grid line and since the default LineStyle used by plot is a solid line, they will automatically be connected. What that code is doing is creating all permutations of endpoints and plotting those to form the grid.

Rather than creating custom plot objects (if you're using R2015b or later), you can simply use the minor grid lines and modify the locations of the minor tick marks of the axes.

g_x = -25:1.25:0;
g_y = -35:2.5:-5;

ax = axes('xlim', [-25 0], 'ylim', [-35 -5]);

% Turn on the minor grid lines
grid(ax, 'minor')

% Modify the location of the x and y minor tick marks
ax.XAxis.MinorTickValues = g_x;
ax.YAxis.MinorTickValues = g_y;

enter image description here

Upvotes: 1

Julian
Julian

Reputation: 979

Basically the code does this:

g_x = -25:1.25:0;

generates a array with values -25.0000 -23.7500 -22.5000 -21.2500 ... 0 These are the positions where vertical lines are drawn

The same holds for g_y, but of course this determines where horizontal lines are drawn. The option 'k' determined that it is a dashed line.

And the loops just loo through the arrays. So in the first iteration the plot function draws a line from the position

[-25, -35]

to the position

[-25, -5]

So if you want to change the grid, just change the values stored in g_x

g_x = -25:3.0:0;

would for example draw vertical lines with the width 3.0 I hope this makes sense for you.

Upvotes: 1

Related Questions