ghostcoder
ghostcoder

Reputation: 81

How to generate the matrix [2,1,1,...,1,2] in MATLAB?

I want to generate a 1 x 50 matrix of the form

[2 1, 1, ..., 1, 2]

My thinking is:

ones(1,50)+[1,0.....,1]

but how to get the [1,0.....,1]? Do I need some for loop?

Upvotes: 1

Views: 64

Answers (1)

Wolfie
Wolfie

Reputation: 30047

Use the indices myArray(1) and myArray(end) to change the first and last elements.

myArray = ones(1,50);
myArray(1) = 2; myArray(end) = 2;

If you know the array is always length 50, you can simply do

myArray = [2, ones(1,48), 2];

Upvotes: 3

Related Questions