1
votes

I have two datasets, lets say data1 and data2. data1 is a 20x12 matrix and data2 is a 12x6 matrix. I want to create a new matrix X, which will contains the following:

The first cell will be the summarize of the element-wise multiplication of the 1st row of data1 with the 1st column of data2. The first element of the second row will be the summarize of the element-wise multiplication of the 2nd row of data1 with the 1st column of data2. ...The first element of the 20th row will be the summarize of the element-wise multiplication of the 20nd row of data1 with the 1st column of data2.

In a similar way it must be the rest columns. For example, the second cell of the first row will be the summarize of the element-wise multiplication of the 1st row of data1 with the second column of data2, etc. i tried the following but i'm not familiar with programming in Matlab and generally with mathematics,

data1 = xlsread(...); % i insert the datasets
data2 = xlsread(...);

for i=1:20
    for j=1:6
data3 = sum(data1(i,:).*data2(:,j));
    end
end

but it doesn't work, can someone help me figure out how to do it or give me a link to work with? Thanks in advance!

2

2 Answers

0
votes

Problem With your code

There are 3 issues with your code:

  1. sizes mismatch: data1(i,:) is of size 1x12 while data2(:,j) is of size 12x1. In order to multiply them, you'll need to use the transpose of one of them.

  2. improper assignment: data3 is being overrided on every iteration, you should use i,j indices to perform a proper assignment.

  3. initialization: The best usage would be to initialize data3 before running the for loop.

Handling these issues

The following code handles all the problems mentioned above:

data3 = zeros(20,6);
for i=1:20
    for j=1:6
        data3(i,j) = sum(data1(i,:)'.*data2(:,j));
    end
end

Better Solution

You can actually achieve the same results with regular matrix multiplication. This can be done as follows:

data3 = data1*data2;
0
votes

You are looking for the matrix multiplication:

data3 = data1 * data2;

This is an elementary operation in linear algebra, hence it's easy to compute in MATLAB.