Creating a simpsons rule matrix

조회 수: 4 (최근 30일)
Joshua Prosper
Joshua Prosper 2020년 2월 22일
편집: John D'Errico 2020년 2월 22일
I want to create a matrix that repeats the numbers 4, 2 for 500 values but has a 1 in the 1st and last spot in each row
for 99 rows
ex: 1 4 2 4 2 4 2 4 ... 4 1
1 4 2 4 2 4 2 4 ... 4 1
1 4 2 4 2 4 2 4 ... 4 1
1 4 2 4 2 4 2 4 ... 4 1

채택된 답변

John D'Errico
John D'Errico 2020년 2월 22일
편집: John D'Errico 2020년 2월 22일
Simple. Just create a matrix that alternates 4, then 2, then 4, etc. Then append a new first and last element of 1 to the result.
So, you could use a tool like repmat to do most of the work. For example:
repmat([4 2],1,4)
ans =
4 2 4 2 4 2 4 2
See that it will always end with a 2. So, append a 1 at the beginning, and [4 1] at the end.
[1,repmat([4 2],1,4),[4 1]]
ans =
1 4 2 4 2 4 2 4 2 4 1
As you can see, the above worked simply, and quite well. I could also have used mod to do the heavy work.
v = [1,mod(1:9,2)*2+2,1]
v =
1 4 2 4 2 4 2 4 2 4 1
Finally, it looks like you want a result that has multiple rows, all the same. Use repmat, replicating one row into many rows!

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by