dexterdev
dexterdev

Reputation: 537

How to get the logical matrix corresponding to "scatter" plot?

If I have a two column matrix A like below, I can plot the scatter plot using scatter/plot command. I would like to get the matrix corresponding to such outputs as in hist command. hist command gives the vector output too.

A=[7 1;3 2; 4 3]

For example out=scatter(A(:,1),A(:,2)) must give something like below:

[0 0 0;
 0 0 0;
 0 1 0;
 0 0 1;
 0 0 0;
 0 0 0;
 1 0 0]

Only the indices (7,1), (3,2) and (4,3) are only ones. Or Can someone give me a snippet code to realize this without using loops?

Upvotes: 1

Views: 403

Answers (3)

dexterdev
dexterdev

Reputation: 537

Here is my solution. Matlab provides a command called accumarray.

S = logical(accumarray(A, 1) )

will give the result too.

Upvotes: 3

Florian
Florian

Reputation: 1824

Just to add: rayryeng's solution is fine if you really want your result to be logical in the sense that it is equal to one if there is anything at the coordinate and zero otherwise. Still, since you added a note on hist, I was wondering if you actually want to count the number of times a specific coordinate is hit. In this case, consider using

S = histcounts2(A(:,2),A(:,1));

if you have access to R2015b+. If not, there is a hist2 function on fileexchange you can use for the purpose.

Upvotes: 3

rayryeng
rayryeng

Reputation: 104545

You can use a combination of sparse and full where you can specify the non-zero row and column locations, and the rest of the matrix would be zero:

A = [7 1; 3 2; 4 3];
B = full(sparse(A(:,1), A(:,2), 1, max(A(:,1)), max(A(:,2)))) == 1;

The sparse command takes in the row and column locations of what is non-zero for the first two inputs, the third input is what the non-zero location would be for each row and column location. We can specify a constant to mean that every non-zero location gets the same coefficient, which is 1. We can also specify the size of the matrix, where in this case the rows and columns of the output correspond to the largest number in the first and second columns respectively. Because this is a sparse matrix, you will want to convert this to a full matrix and because you want it to be logical, you will want to compare all elements with the number 1.

We thus get for the output, which is B:

B =

  7×3 logical array

   0   0   0
   0   0   0
   0   1   0
   0   0   1
   0   0   0
   0   0   0
   1   0   0

Alternatively, we can use sub2ind to create linear indices to index into a pre-allocated matrix of logical false and set only those non-zero row locations to true:

A = [7 1; 3 2; 4 3];
B = false(max(A(:,1)), max(A(:,2)));
ind = sub2ind(size(B), A(:,1), A(:,2));
B(ind) = true;

We first allocate the matrix, then calculate the linear indices to index into the matrix, then finally set the right locations to true. The output here would be the same as the sparse approach.

Upvotes: 3

Related Questions