在matlab中绘制稀疏矩阵

时间:2014-09-24 21:18:09

标签: image matlab plot sparse-matrix

我想在imagesc类型的样式中绘制稀疏矩阵(每个像素一种颜色,而不是la scatter的符号)。矩阵由遍布10000x10000平方的斑点组成。我预计大约有100个blob,每个blob是50x100像素。这个矩阵非常大,放大或缩小或在其中移动以检查数据变得非常迟缓。我仍然想保持决议。有没有办法绘制稀疏矩阵,只绘制斑点,并将色图的“零色”作为背景,不占用内存空间?

假设我们有一个矩阵M看起来像这样:

[1, 2,  1, 0;
 0, 1, .4, 0;
 0, 0,  0, 0;
 0, 7,  0, 0]

当我将其绘制为稀疏矩阵时

figure; 
imagesc(sparse(M));

它与省略sparse-command的大小相同。这就是我想要规避的。

1 个答案:

答案 0 :(得分:5)

您可以只绘制非零值,而不是将矩阵视为图像。使用scatter(而不是plot)可以让颜色作为值的函数,就像在imagesc中一样。

默认情况下scatter会将背景保留为白色,因此您必须对其进行调整。这是通过两个步骤完成的:确保scatter的颜色缩放将颜色映射的第一种颜色指定为值0;然后手动设置轴'那种颜色的背景。

但是,我还没有测试过这会占用更少的内存。

%// Generate example matrix
M = 10000*rand(1000);
M(M>100) = 0;
M = sparse(M); %// example 1000x1000 matrix with ~1% sparsity

%// Do the plot
cmap = jet; %// choose a colormap
s = .5; %// dot size
colormap(cmap); %// use it
[ii, jj, Mnnz] = find(M); %// get nonzero values and its positions
scatter(1,1,s,0) %// make sure the first color corresponds to 0 value.
hold on
scatter(ii,jj,s,Mnnz); %// do the actual plot of the nonzero values
set(gca,'color',cmap(1,:)) %// set axis backgroud to first color
colorbar %// show colorbar

注意轴'方向可能与imagesc不同。

enter image description here