Problems with loops in matrix operations

5 Ansichten (letzte 30 Tage)
SAÚL
SAÚL am 12 Apr. 2023
Beantwortet: Joe Vinciguerra am 12 Apr. 2023
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

Antworten (2)

Vilém Frynta
Vilém Frynta am 12 Apr. 2023
Bearbeitet: Vilém Frynta am 12 Apr. 2023
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 am 12 Apr. 2023
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.

Kategorien

Mehr zu Multidimensional Arrays finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by