Problems with loops in matrix operations

조회 수: 6 (최근 30일)
SAÚL
SAÚL 2023년 4월 12일
답변: Joe Vinciguerra 2023년 4월 12일
First of all, sorry if you guys don't understand some expressions, because i'm not a native english speaker.
I am trying to make a loop for a matrix multiplication. I have this matrixes, where "matrix1" is 432x27; "matrix2" is 16x67 and "matrix3" is 1072x67 (filled of zeros). My idea is doing a loop to select a 16x1 vector from matrix1 from first colum, and multiplicate each element (.*) with matrix2, and finally put the result in matrix3.
The thing is, in the first round, i want to select the first 16 (from 1 to 16) rows of the first column of matrix 1 for the multiplication; the next round, i want to select the next 16 rows (i mean, from row 17 to row 32) of the second column of matrix 1 for the multiplication, and so on.
This is what i have right now, but each time i evaluate this commands, i get this error: "Arrays have incompatible sizes for this operation".
b=0
for i=1:27
for j=1:27
emematrix1=matriz1(b*16+1:j*16,i).*matrix2;
matrix3(b*16+1:j*16,:)=emematrix1;
end
b=b+1
end

답변 (2개)

Vilém Frynta
Vilém Frynta 2023년 4월 12일
편집: Vilém Frynta 2023년 4월 12일
To fix this, you need to transpose the 16x1 vector from matrix1 so that it becomes a 1x16 row vector. This way, when you multiply it with the 16x67 matrix2, the sizes will match.
However, it would be best to post your matrices so we can work in them, in case my advice doesn't help.

Joe Vinciguerra
Joe Vinciguerra 2023년 4월 12일
It looks like you want b=0 in the first loop and b=b+1 in the second loop. Otherwise, when j=2 and b=0 the matrix1 subarray becomes 32x1 instead of 16x1, resulting in that error. Try this:
matrix1 = rand([432 27]);
matrix2 = rand([16 67]);
matrix3 = zeros([1072 67]);
for i=1:27
b=0;
for j=1:27
emematrix1=matrix1(b*16+1:j*16,i).*matrix2;
matrix3(b*16+1:j*16,:)=emematrix1;
b = b+1;
end
end
Alternately, instead of b you could use j-1, since b will always be one less than j in this case.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by