irJvV
irJvV

Reputation: 912

Octave model matrix

Is there a simple (non for loop) way to create a model matrix in Octave. In R i use model.matrix() to do this.

I have this array:

array = [1;2;3;2]

and i need (for regression reasons)

*(model = [1 0 0 0; 0 1 0 1; 0 0 1 0])* EDIT on my side
result is this model (colum 1 is for 1, column 2 for the two's etc.:
model = [1 0 0 ; 0 1 0 ; 0 0 1 ; 0 1 0]

I can do this with a for loop:

model = zeros(4,3);

for i=1:4
 model(i,array(i)) = 1; 
end

but it would be nice to do this in one step something like:

model = model.matrix(array)

i can than include it in a formula straight away

Upvotes: 0

Views: 53

Answers (1)

carandraug
carandraug

Reputation: 13081

You need to turn your values into linear indices like so:

octave:1> array = [1 2 3 2];
octave:2> model = zeros ([numel(array) max(array)]);
octave:3> model(sub2ind (size (model), 1:numel(array), array)) = 1
model =

   1   0   0
   0   1   0
   0   0   1
   0   1   0

Because your matrix will be very sparse, a possible optimization is to create a sparse matrix instead.

octave:4> sp = sparse (1:numel(array), array, 1, numel (array), max (array))
sp =

Compressed Column Sparse (rows = 4, cols = 3, nnz = 4 [33%])

  (1, 1) ->  1
  (2, 2) ->  1
  (4, 2) ->  1
  (3, 3) ->  1

octave:5> full (sp)
ans =

   1   0   0
   0   1   0
   0   0   1
   0   1   0

This will take a lot less memory but many functions will be unable to handle them and convert them to a full matrix anyway. So whether this is worth is dependent on what you want to do next.

Upvotes: 1

Related Questions