MATLAB: How can i represent elevation (z) in different colors using plot function

colorbarplotwith

I' am plotting distance (h) which is the x-axis against elevation (z)which is y-axis using the plot function in MATLAB.
The output figure i get is a single red line. But i want to represent the single line in different colors according to elevation with a color bar
cheers

Best Answer

That's not a straightforward thing to do;
h = axes;
x = (1:10)';
y = rand(1,10);
minY = min(y);
intY = max(y) - minY;
lH = plot(x,y); hold on
colors = colormap('jet');
numDiv = 100;
for ii = 2 : numel(x);
sub_x = linspace(x(ii-1),x(ii),numDiv);
sub_y = linspace(y(ii-1),y(ii),numDiv);
for jj = 2 : numel(sub_y)
temp_y = (sub_y(jj-1) + sub_y(jj) ) / 2;
idx = ceil( (temp_y - minY) ./ intY * size(colors,1));
plot([sub_x(jj-1) sub_x(jj)], [sub_y(jj-1) sub_y(jj)], ...
'Linestyle','-','Color',colors(idx,:));
end
end
delete(lH)
set(h,'CLim',[min(y),max(y)]);
colorbar;