# How can I solve a linear system of equation Ax=b where A and b are changing in a for loop

7 views (last 30 days)
Luca Amicucci on 16 Sep 2020
Commented: Luca Amicucci on 17 Sep 2020
Hi there.
I'm doing a dynamic force analysis problem and i need to determinate forces and torque on a four-bar linkage.
So I wrote a linear system Ax = b , but this is in a for loop (i = 1:360) and the components of A and b change at every step. (see photo)
For matrix A, I thought I need a 9x9 matrix that changes ad every step so,
for i = 1:360
.....
.....
A(9, 9, i) = [ 1,0,-1,0,0,0,0,0,0;
0,1,0,-1,0,0,0,0,0;
Ra2y(i),-Ra2x(i),Rb2y(i),-Rb2x(i),0,0,0,0,1;
0,0,1,0,-1,0,0,0,0;
0,0,0,1,0,-1,0,0,0;
0,0,-Rb3y(i),Rb3x(i),Rc3y(i),-Rc3x(i),0,0,0;
0,0,0,0,1,0,1,0,0;
0,0,0,0,0,1,0,1,0;
0,0,0,0,-Rc4y(i),Rc4x(i),-Rd4y(i),Rd4x(i),0];
and
b(9,1,i) = [m2*ag2x(i);
m2*ag2y(i) - W2;
Ig2*alfa2(i);
m3*ag3x(i);
m3*ag3y(i) - W3;
Ig3*alfa3(i);
m4*ag4x(i);
m4*ag4y(i) - W4;
Ig4*alfa4(i)];
and then calculate x = A\b where x is a 9x1x360, so 360 column vector 9x1;
But matlab tell me "Unable to perform assignment because the indices on the left side are
not compatible with the size of the right side";
I don't know what to do..
Anyone can help me ?
Sorry for my not-so-perfect english.
Luca

Jon on 16 Sep 2020
Edited: Jon on 16 Sep 2020
You could do it like this:
% preallocate arrays to hold results
x = zeros(9,360);
A = zeros(9,9,360);
b = zeros(9,1,360);
% loop through angular positions
for i = 1:360
A(:,:,i) = ... % assign all rows and and all columns of 9 by 9 to the ith "page"
b(:,i) = ... % assign all rows of 9 by 1 to the ith "page"
% solve and store result in ith column of x result matrix
x(:,i) = A\b
end
By the way, I see you are storing the A and b matrices as 3 dimensional arrays, if you don't need them after the analysis is done you don't need to save them at all, you could just compute A and B at each increment. In this case don't preallocate the A an b arrays and just assign A = ... and b = ...
Finally, It's good to avoid screenshots of code. Instead if you want to include code in your post you can use the "Code" button in the MATLAB Answers toolbar to have it formatted nicely.

Luca Amicucci on 16 Sep 2020
Ahhh you’re right, it’s more efficient. Thanks again! Can I ask you another question ?
Jon on 17 Sep 2020
yes of course, but if it's a completely new topic you might want to post it as a new question in case other people might be interested in following it.
Luca Amicucci on 17 Sep 2020
Ok, I post a new question.

R2019b

### Community Treasure Hunt

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

Start Hunting!