MATLAB: Creating a simpsons rule matrix

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

Best Answer

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!
Related Question