Creating a simpsons rule matrix

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

 采纳的回答

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 个)

类别

在 帮助中心 和 File Exchange 中查找有关 Linear Algebra 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by