How can I create a matrix that looks like "plot(k1,k2,'r*')" in MATLAB?

5 views (last 30 days)
I have two vectors "k1" and "k2". When I run
 
>> plot(k1, k2, 'r*')
I get an image with dots. I want to make a matrix that looks like the plot. The places with no dots could have NaN or 0 in them. 
How can I do that? 
Thanks. 

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 23 Apr 2014
One way to create a matrix that looks like "plot(k1, k2, 'r*')" would be to:
 
   1. Create a matrix of zeros.
   2. Transform "k1(i)" and "k2(i)" into coordinates suitable for the matrix.
   3. Assign a non-zeros value to these coordinates.
 
 *1. Create a matrix of zeros*
 
For example, you could define the size of the matrix using the x- and y-axis limits of the plot:
 
figure;
plot(k1, k2, 'r*')
xlimits = xlim;
ylimits = ylim;
x = linspace(xlimits(1), xlimits(2), numel(k1));
y = linspace(ylimits(1), ylimits(2), numel(k2));
 
Here, variables "x" and "y" are vectors of indices corresponding to the plot. Then, the matrix can be created using the sizes of "x" and "y":
 
M = zeros(length(y), length(x));
 *2. Transform "k1(i)" and "k2(i)" into coordinates suitable for the matrix*
 
Now, we want to find the indices "x(i)" and "y(i)" corresponding to where a data point is plotted, i.e. a data point with position "k1(i), k2(i)". You can use the "histc" function to do that. The "histc" function creates a histogram by counting the elements that fall in each bin. In our case, the bins will be represented by the vectors of indices "x" and "y" and the data will be "k1" and "k2". We are not interested in the histogram itself, but using"histc" we can find the position of each data point in the matrix. This is represented by the second output argument of the function:
 
[~, indx] = histc(k1, x);
[~, indy] = histc(k2, y);
 
Variables "indx" and "indy" represent the coordinates that contain a data point.
 *3. Assign a non-zeros value to these coordinates*
Now, all we have to do is fill the matrix "M" with non-zero values where "indx" and "indy" are both non-zero. The "sub2ind" function can be used to transform subscript indices "indx" and "indy" into linear indices that can directly be passed to the matrix "M":
 
ind = sub2ind(size(M), indy, indx);
 
Finally:
 
M(ind) = 1;
 
Matrix "M" will be 0 where there is no data point and 1 where there is a data point. You can check that matrix "M" looks similar to the plotted data by displaying it as an image:
 
figure;
imshow(M)
set(gca, 'YDir','normal')

More Answers (0)

Categories

Find more on Graphics Object Programming in Help Center and File Exchange

Tags

No tags entered yet.

Products

Community Treasure Hunt

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

Start Hunting!