RGB圖像是一個M*N*3的3維矩陣組成的圖像。
簡單的說cat函數的主要功能是合成矩陣:
cat(1,A,B):合成1維矩陣。
cat(2,A,B):合成2維矩陣。
cat(3,A,B,C):合成3維矩陣。
cat(dim,Y0,Y1,Y2,Y3...............)
是按dim的位數來合成矩陣。
對圖像生成而言,取dim=3,然后將3個分別代表RGB分量的矩陣連接在一起:
photo=cat(3,red,green,blue)
這里red,blue,green為別為生成RGB圖像photo的三個分量的值,可以使用下列語句:
rgb_r=photo(:,:,1);
rgb_g=photo(:,:,2);
rgb_b=photo(:,:,3);
例子1:

1 clear
2 rgb_R=zeros(8,256);
3 rgb_G=zeros(8,256);
4 rgb_B=zeros(8,256);
5 zero=zeros(8,256);
6
7 for i=1:256
8 rgb_R(:,i)=i;
9 rgb_G(:,i)=i;
10 rgb_B(:,i)=i;
11 end
12 red=uint8(rgb_R);
13 green=uint8(rgb_G);
14 blue=uint8(rgb_B);
15
16 R=cat(3,red,zero,zero);
17 G=cat(3,zero,green,zero);
18 B=cat(3,zero,zero,blue);
19 RG=cat(3,red,green,zero);
20 RB=cat(3,red,zero,blue);
21 GB=cat(3,zero,green,blue);
22
23 subplot(6,1,1), imshow(R), title('紅色全彩圖');
24 subplot(6,1,2), imshow(G), title('綠色全彩圖');
25 subplot(6,1,3), imshow(B), title('藍色全彩圖');
26 subplot(6,1,4), imshow(RG), title('紅色和綠色復合全彩圖');
27 subplot(6,1,5), imshow(RB), title('紅色和藍色復合全彩圖');
28 subplot(6,1,6), imshow(GB), title('綠色和藍色復合全彩圖');
結果:
例子2:
上篇中是定義了一個空的JPG圖像,然后替換掉紅色部分。
這次直接用CAT函數定義。

1 clear;
2 green=zeros(1080,1920);
3 zero=zeros(1080,1920);
4 a=textread('green.dat','%s')';
5 b=hex2dec(a);
6 c=uint8(b);
7 for i=1:1080
8 for j=1:1920
9 m=1920*(i-1)+j;
10 green(i,j)=c(m);
11 end
12 end
13 rgb_G=uint8(green);
14 RGB=cat(3,zero,rgb_G,zero);
15 imshow(RGB);
結果: