1
votes

I am trying to figure out how scatter function works in matlab. For example , I have the two matrices:

 mat1= rand(20,20)
 mat2= rand(20,20)

At this point I need to open a figure and use the “scatter” function to display a scatter plot of the values in mat1 versus the values in mat2. What I did is:

figure()
scatter(mat1,mat2)

Obvious that is wrong. But I dont know how to do that. In addition I read the documentations about scatter function in matlab docs Scatter Function - MATLAB DOCS

Suggestions are welcomed! thanks.

3

3 Answers

3
votes

Since scatter function expects vectors (Matrixes with either one row or one column), try

figure()
scatter(mat1(:),mat2(:))

The (:) operator turns matrixes into vectors.

0
votes

Scatter is just a way of ploting data. Scatter will plot data as points without connecting them. try

mat1= rand(1,20) 
mat2= rand(1,20) 
subplot(121) 
scatter(mat1,mat2); 
subplot(122) 
plot(mat1,mat2) 

enter image description here

0
votes

This answer is in response to the OP's comment requesting how to set different markers to different colors.

Approach 1: Logical Indexing
Requires you to define the index for each color. In the example below, red markers are selected randomly; the remaining markers will be blue.

2D Scatter plot using different colors via logical indexing

% MATLAB R2017a
mat1 = 100*rand(20,1);
mat2 = 100*rand(20,1);

idxRed = rand(20,1)> 0.5;
idxBlue = ~idxRed;

s(1) = scatter(mat1(idxRed),mat2(idxRed),[],'r','filled');
hold on
s(2) = scatter(mat1(idxBlue),mat2(idxBlue),[],'b','filled');

% Cosmetics
daspect([1 1 1])
box on
for j = 1:2
    s(j).MarkerEdgeColor = 'k';    
    s(j).MarkerFaceAlpha = 0.3;    % Transparency control
end

Approach 2: Custom Colormap
Create a custom colormap that directly maps to colors you want. In the example below, the color map only contains two colors. The logical variable idxRed only has two possible values, so the call caxis([0 1]) is unnecessary here.

2D Scatterplot with markers colored using colormap

% Create custom colormap  
col1 = [0 1 0]; % Green 
col2 = [1 0 0]; % Red
cmap = [col1;col2];
% Plot
colormap(cmap), hold on, box on
scatter(mat1,mat2,[],idxRed,'filled');