Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select a different base for a logarithmic plot in matlab

Tags:

matlab

I want to have the x-axis logarithmic to the base 2: From 2^10 to 2^25 and at each step the exponent should increase by one, while the y-axis should be linear.

How is this possible? I already figured out

set(gca,'XScale','log')

but u can't set the base.

like image 776
Nils Avatar asked Oct 07 '10 12:10

Nils


People also ask

How do you do log base 2 in MATLAB?

Y = log2( X ) returns the logarithm to the base 2 of X such that 2Y = X. If X is an array, then log2 acts element-wise on X . [ F , E ] = log2( X ) returns arrays of mantissas and exponents, F and E , such that X = F ⋅ 2 E . The values returned in F are in the range 0.5 <= abs(F) < 1 .

What is the base of the MATLAB function log?

You don't have to define the base. Just write log(14-y). In matlab , log(x) means ln(x). Sign in to answer this question. I have the same question (0)

How logarithmic plots can be plotted in MATLAB explain?

Create a vector of x-coordinates and two vectors of y-coordinates. Plot two lines by passing comma-separated x-y pairs to loglog . Alternatively, you can create the same plot with one x-y pair by specifying y as a matrix: loglog(x,[y1;y2]) .

What does Semilogy function do in MATLAB?

As the definition says in MATLAB help section: semilogy(Y) creates a plot using a base 10 logarithmic scale for the y -axis and a linear scale for the x -axis. It plots the columns of Y versus their index if Y contains real numbers.


2 Answers

Consider this example:

%# some random data
x = 2.^(0:10);
y = rand(size(x));

plot(log2(x), y)                               %# plot on log2 x-scale
set(gca, 'XTickLabel',[])                      %# suppress current x-labels

xt = get(gca, 'XTick');
yl = get(gca, 'YLim');
str = cellstr( num2str(xt(:),'2^{%d}') );      %# format x-ticks as 2^{xx}
hTxt = text(xt, yl(ones(size(xt))), str, ...   %# create text at same locations
    'Interpreter','tex', ...                   %# specify tex interpreter
    'VerticalAlignment','top', ...             %# v-align to be underneath
    'HorizontalAlignment','center');           %# h-aligh to be centered

alt text

like image 53
Amro Avatar answered Sep 20 '22 15:09

Amro


You can plot directly using the plot command

plot (log2(x), y)

but then your x ticks will be the logarithm rather than the actual value. You could either just change your label

xlabel('Log (base 2) of quantity X');

or you can redo the ticks manually.

xt = get(gca, 'XTick');
set (gca, 'XTickLabel', 2.^xt);

Or you can be really fancy

xticks = 10:25;
set(gca, 'XTick', xticks);
for j = 1:length(xticks)
  xtl{j} = ['2^' num2str(xticks(j))];
end
set(gca, 'XTickLabel', xtl)

which will evenly space the tick marks on the log scale, and label them according to their power of 2

like image 25
Marc Avatar answered Sep 20 '22 15:09

Marc