I have several different files where I have to multiply the columns by each other, and they are of different size. However I keep getting the error "Error using .* Matrix dimensions must agree.
I was led to believe that if you use (.*), the size of the columns did not matter. I developed an example matrix with exactly the same values, in exactly the same order, and that worked, however this is not an option as I have many files that I have to execute this equation.
The code for my example (which worked), is as follows:
Example(:,3)=Example(:,1).*Example(:,2);
The code for my actual problem (which did not work) is as follows:
OWC1_Power.F020(:,1)=Pf020006(:,7).*dzdt.Wf020(:,7)
OWC1_Power.F020, is the matrix where I want the answer to be stored, Pf020006 is an imported matrix, and dzdt.Wf020 is another imported matrix.
Does anyone have any ideas why this error is occurring?

답변 (1개)

Guillaume
Guillaume 2016년 3월 15일

0 개 추천

I was led to believe that if you use (.*), the size of the columns did not matter. Whoever led you to believe this was completely wrong. If anything, the size of the matrices matter even more with .* than *, they must be the exact same size in all dimensions.
In any case, * and .* are two completely different operations ( matrix multiplication and elementwise multiplication respectively) and replace one by the other just because one does not work is unlikely to get the result you want. It may not cause an error but it won't give the right value, if that's not what you meant to do.
There's no way to solve your problem until you define what I have to multiply the columns by each other means when two columns have different size.

댓글 수: 2

Alex Mott
Alex Mott 2016년 3월 15일
elementwise multiplication is what I was after. And I checked through the answers from my example matrix and it worked fine.
With "multiply the columns by each other", I meant elementwise multiplication from a column in one matrix, by a column in another matrix. The two columns are different sizes for each matrix I have. I need elementwise multiplication from, for example; one matrix has 10 rows in a column, the other has 15 rows in a column, I need elementwise multiplication from 1-10, and the 11-15 in the latter matrix, can be disregarded. I expected for the results for 11-15 to equate to NaN, however this was not the case for my actual problem. Whereas in the example problem, this occurred.
To do the multiplication according to your definition, you need to truncate the longer column:
function out = columnmult(a, b);
%a and b are column vectors. No validation here
minlength = min(size(a, 1), size(b, 1);
out = a(1:minlength, :) .* b(1:minlength, :);
end
>>OWC1_Power.F020(:,1)=columnmult(Pf020006(:,7, dzdt.Wf020(:,7))

댓글을 달려면 로그인하십시오.

카테고리

질문:

2016년 3월 15일

댓글:

2016년 3월 15일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by