For the 1-D case dealing with a set of vectors, the other answers point out the correct solutions (involving padding the shorter vector with zeroes or performing the addition using a subindex into the longer vector). However, since you mentioned in a comment that you are ultimately wanting to add two grayscale images together, I thought I d show you a more general 2-D solution for matrices.
First, I ll load some built-in MATLAB sample images and get their sizes:
image1 = rgb2gray(imread( peppers.png ));
image2 = imread( cameraman.tif );
[r1, c1] = size(image1);
[r2, c2] = size(image2);
Notice that I converted the RGB image to grayscale first using rgb2gray
. Next, I ll make a new matrix of zeroes whose size is the maximum of the sizes of the two images:
newImage = zeros(max(r1, r2), max(c1, c2), uint8 );
Notice that I included uint8
in the call to zeros
, since you want the matrix of zeroes to be the same type as your images so that subsequent operations on them will work correctly. The matrix newImage
is now large enough to contain either of the two images. Finally, the images can be added to the new image like so:
newImage(1:r1, 1:c1) = image1; % Insert image 1
newImage(1:r2, 1:c2) = newImage(1:r2, 1:c2)+image2; % Add image 2
And you can view them with the following:
imagesc(newImage);
colormap(gray);
NOTE: One important thing to consider is the type you use for the images. Normally, image data that is loaded into MATLAB is of type uint8
. However, you may notice that adding two 8-bit unsigned integer images as I did above can result in saturation where pixels exceed the value of 255 (the maximum value for an 8-bit unsigned integer). The result is that parts of the image look bright white and lose detail (notice some of the peppers that overlap the smaller image above). You may want to avoid this by scaling the values in your images before adding them, or by converting your images to type double
to perform the operations and then scaling them before resaving the image.