Nested While Loops Not Updating?
Afficher commentaires plus anciens
Pardon, a bit new to this language. I've been working on this matrix multiplier for awhile now, and it should run smoothly, except that it appears the code doesn't update itself as necessary. Here's the troublesome code (the matrices are given, but can be substituted with any matrix):
firstMatrix = importdata('hw41matA.txt');
secondMatrix = importdata('hw41matB.txt');
[nRowA,colA] = size(firstMatrix);
[rowB, nColB] = size(secondMatrix);
finalResult = zeros(nRowA,nColB);
toAdd = zeros(1,3);
rowToMultA = 1;
colToMultB = 1;
insideColToMultB = 1;
insideRowToMultA = 1;
sumHelp = 1;
sum = 0;
help = 1;
while (rowToMultA <= nRowA)
while (colToMultB <= nColB)
while (insideColToMultB <= nRowA)
toAdd(1,insideColToMultB) = firstMatrix(rowToMultA,insideColToMultB)*secondMatrix(insideColToMultB,colToMultB);
sum = sum+toAdd(1,insideColToMultB);
insideColToMultB = insideColToMultB+1;
end
finalResult(rowToMultA,colToMultB) = sum;
help = help+1;
colToMultB = colToMultB+1;
end
rowToMultA = rowToMultA+1;
colToMultB = 1;
end
On its own the code will correctly generate and place the first answer, but then get "stuck" on calculating that row and column number and continue to fill in that answer for the rest of the results matrix. So, for example, on its own the code would show finalResult = [32,32,32;32,32,32;32,32,32]
Now If I manually specify the row and column numbers (for example, rowToMultA = 1; colToMultB = 2;) inside the third while loop (under while(insideColToMultB <= nRowA)), then the code is able to correctly calculate and place that space's answer. But then for the following spaces it gets stuck again. (Using the above "fix" one gets finalResult = [0,23,23;23,23,23;23,23,23] )
It would seem the rowToMultA and colToMultB are updating enough to rightfully place the answers in the finalResult matrix, but are not updating within the third while loop so that each answer actually correctly corresponds to each place. I've tried reordering the code but that only brings the final result farther from what it should be.
Any help?
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!