From equation to matrix with for loop

12 views (last 30 days)
How can somone change equation into matrix with a for loop? For example if you have something like this:
for i = 1:10
1*x(i) + 2*x(i+1) + 3*x(i+2) = y(i)
end
So, if I were to do this by hand it would be like for i =1
[ 1 2 3 ] * [ x(1) x(2) x(3)]' = y(1)
and for i = 2 you will have
[ 1 2 3 ] * [x(2) x(3) x(4)]' = y(2)
so how can I structure this in a way it gives me a matrix that looks like this:
[ 1 2 3 0; 0 1 2 3] * [x(1) x(2) x(3) x(4)]' = [y(1); y(2)]
  2 Comments
Bopha NEAK
Bopha NEAK on 18 Sep 2021
for i = 1:10
1*x(i) + 2*x(i+1) + 3*x(i+2) = y(i)
end
Image Analyst
Image Analyst on 18 Sep 2021
@Bopha NEAK, You can't have the y be on the right side of the equal sign. It must be on the left. See my answer below.

Sign in to comment.

Accepted Answer

Image Analyst
Image Analyst on 18 Sep 2021
Do you mean like this:
x = 1 : 12
numRows = 3; % Whatever you want.
y = zeros(numRows, length(x)); % Preallocate.
for row = 1 : numRows
for col = row : length(x) - 2 % Can't have col+2 be longer than x
y(row, col) = 1*x(col) + 2*x(col+1) + 3*x(col+2);
end
end
y
x =
1 2 3 4 5 6 7 8 9 10 11 12
y =
14 20 26 32 38 44 50 56 62 68 0 0
0 20 26 32 38 44 50 56 62 68 0 0
0 0 26 32 38 44 50 56 62 68 0 0
  2 Comments
Io7
Io7 on 18 Sep 2021
Edited: Io7 on 18 Sep 2021
Thank you for your reply, that really helped, but I wanted to know if there is a way to make Matlab do it instead of specifiying the number of rows because for example if I have like a large matrix, It will be hard to try to specify the number of X's so I won't be able to tell the number of rows
also for this 1*x(i) + 2*x(i+1) + 3*x(i+2) = y(i) I'm just trying to make it simple as possible but it can be more complicated like 1*x(i) + 2*x(i+1) + 3*x(i+2) = y(i)+y(i-1)/2
but what I'm trying to know if there is a way matlab can arrange the matrix for me and structure it the way I want
so for the example I gave
So, if I were to do this by hand it would be like for i =1
[ 1 2 3 ] * [ x(1) x(2) x(3)]' = y(1)
and for i = 2 you will have
[ 1 2 3 ] * [x(2) x(3) x(4)]' = y(2)
and for i = 3 you will have
[ 1 2 3 ] * [x(3) x(4) x(5)]' = y(3)
so I want matlab to structure my matrix in this form
[ 1 2 3 0 0; 0 1 2 3; 0 0 1 2 3] and this will be a single matrix <-- I want matlab to generate this matrix for me
[x(1) x(2) x(3) x(4) x(5)]' and this is another matrix
then it will equal to
[ y(1); y(2); y(3)] the result matrix
Image Analyst
Image Analyst on 18 Sep 2021
I really don't know what
1*x(i) + 2*x(i+1) + 3*x(i+2) = y(i)+y(i-1)/2
means. You can't have an assignment like that in MATLAB. Are you trying to do differential equations?

Sign in to comment.

More Answers (0)

Categories

Find more on Performance and Memory in Help Center and File Exchange

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!