Kushan Peiris
Kushan Peiris

Reputation: 167

replacing octave matrix values

I am a beginner to octave. I created a 5x5 matrix named x as follows with all ones

 X=ones(5,5)

I want to replace the all the ones in the last column(5th column) with (-3,+5) but when I give the following command it gives an error

 y(:,5)=(-3,+5)

How can I correct this?

Upvotes: 0

Views: 3996

Answers (1)

Tommaso Belluzzo
Tommaso Belluzzo

Reputation: 23675

Numerical arrays cannot store other arrays as elements. You have to work with cells in order to achieve your goal:

X = num2cell(ones(5));
X(:,5) = {[-3 5]}

X = 
{
  [1,1] =  1
  [2,1] =  1
  [3,1] =  1
  [4,1] =  1
  [5,1] =  1
  [1,2] =  1
  [2,2] =  1
  [3,2] =  1
  [4,2] =  1
  [5,2] =  1
  [1,3] =  1
  [2,3] =  1
  [3,3] =  1
  [4,3] =  1
  [5,3] =  1
  [1,4] =  1
  [2,4] =  1
  [3,4] =  1
  [4,4] =  1
  [5,4] =  1
  [1,5] = -3 5
  [2,5] = -3 5
  [3,5] = -3 5
  [4,5] = -3 5
  [5,5] = -3 5
}

Alternatively, you can build that using two separate steps by concatenating the cell arrays:

X = [num2cell(ones(5,4)) repmat({[-3 5]},5,1)]

EDIT

Following the details in your comment:

X = randi([0 1],5);
idx = X(:,5) == 1; % build an indexer to the elements equal to 1 in column 5

X = num2cell(X); % convert the matrix into a cell array
X(idx,5) = {[-3 5]}; % replace the indexed elements with a vector

Upvotes: 1

Related Questions