How to plot based on the shortest vector?
2 次查看(过去 30 天)
显示 更早的评论
I want to plot two collumns of data against each other but one is longer than the other. The data all lines up and there is only a couple of extra data points at the bottom of the collumn.
Here is the code in question:
patch(po,pa,x,'Facecolor',[0.8,0.8,0.8]);
hold on
AltvO3=plot(O3ave,adj_ave_alt,'-o','Markersize',3,'color','k');
In this case I want pa and x to include up to as many data points in po and adj_ave_alt to include up to as many data points as O3ave.
2 个评论
Rik
2021-6-17
The easiest solution is to write a wrapper function that trims the data as you need and then calls plot or patch with the shortened arrays.
回答(2 个)
Scott MacKenzie
2021-6-18
编辑:Scott MacKenzie
2021-6-19
So, the approach I think you are willing to take is just to ignore the few extra elements that are in the longer of the two vectors. Here's a simple way to do this:
% two column vectors of data with a few extra elements in one of them
c1 = randi([1 100], 20, 1);
c2 = randi([1 100], 18, 1);
% determine the length of the shorter of the two columns of data
n = min(numel(c1), numel(c2));
% plot the data, ignoring the extra elements in the longer vector
patch(c1(1:n), c2(1:n), 'r');
7 个评论
Rik
2021-6-19
I just don't see the merit of using something that has the potential to cause issues, while there is a function that does the exact same thing for vectors, but will not cause unintended behavior for array inputs.
I don't see why you would teach anyone a tool that may bite them, while there are viable alternatives. Can you convince me why numel would be a worse choice?
Scott MacKenzie
2021-6-19
This seems like splitting hairs to me. If you think this is significant, perhaps take it up with MATLAB staff. They could easily add "not recommended" in the documentation, as done with other functions people should avoid.
Rik
2021-6-18
I was just about to comment something along the lines of the answer @Scott MacKenzie posted. The idea is that you find out what the shortest vector is and then call the function you need. The only extra part I was suggesting was a function definition and some documentation:
h=short_plot(rand(10,1),rand(8,1))
function varargout=short_plot(x,y,varargin)
%This functions shortens either x or y to make them equal length and calls
%the plot function. It will forward all optional inputs to plot().
n=min(numel(x),numel(y));
x=x(1:n);y=y(1:n);
varargout=cell(nargout,1);
[varargout{:}]=plot(x,y,varargin{:});
end
You can do the same for your custom patch function.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Introduction to Installation and Licensing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!