From equation to matrix with for loop

조회 수: 13 (최근 30일)
Io7
Io7 2021년 9월 18일
댓글: Image Analyst 2021년 9월 18일
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
Bopha NEAK
Bopha NEAK 2021년 9월 18일
for i = 1:10
1*x(i) + 2*x(i+1) + 3*x(i+2) = y(i)
end
Image Analyst
Image Analyst 2021년 9월 18일
@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.

댓글을 달려면 로그인하십시오.

채택된 답변

Image Analyst
Image Analyst 2021년 9월 18일
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
Io7
Io7 2021년 9월 18일
편집: Io7 2021년 9월 18일
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 2021년 9월 18일
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?

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Performance and Memory에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by