matlab中的矩阵大小

时间:2013-02-18 17:35:35

标签: matlab

我有一个问题,那该怎么办?!

我在matlab中读取了两张不同大小的图像,然后我将它们翻转为双倍 对它们进行操作,但问题是它们的大小不一样 如何使它们与较大的一样,然后用零填充其他空白尺寸?

2 个答案:

答案 0 :(得分:2)

假设您有两个矩阵:

a = 1  2  3 
    4  5  6 
    7  8  9

b = 1  2 
    3  4

您可以这样做:

c = zeros(size(a)) %since a is bigger

将创建:

c = 0  0  0
    0  0  0 
    0  0  0

然后复制较小矩阵的内容(在本例中为b):

c(1:size(b,1), 1:size(b,2)) = b;

size(b,1)返回行数,大小(b,2)返回列数

最终结果将是一个大小为a的矩阵,其中包含b0的值:

c = 1  2  0
    3  4  0
    0  0  0

编辑:

 image1=imread(image1Path); 
 image2=imread(image2Path); 
 image1= double(image1); 
 image2= double(image2); 

 %%%ASSUME image1 is bigger%%%

 new_image = zeros(size(image1));
 new_image(1:size(image2,1), 1:size(image2,2)) = image2;
 %NOW new_image will be as you want.

答案 1 :(得分:0)

您的问题有点模糊,但假设您有两个不同大小的矩阵AB。 现在,如果你总是想用零填充最小的维度,你可以这样做:

rs = max([size(A);size(B)]); % Find out what size you want
A(rs(1)+1,rs(2)+1) = 0; % Automatically pad the matrix to the desired corner (plus 1)
B(rs(1)+1,rs(2)+1) = 0; % Plus one is required to prevent loss of the value at (end,end)
A = A(1:end,1:end); %Now remove that one again
B = B(1:end,1:end);

请注意,无论哪个更大,哪个更高,而另一个更宽,这都有效。当您想使用if语句时,这可能更容易理解:

rs = max([size(A);size(B)]); % Find out what size you want
if any(size(A) < rs)
     A(rs(1),rs(2)) = 0;
end
if any(size(B) < rs)
     B(rs(1),rs(2)) = 0;
end
相关问题