wrongusername
wrongusername

Reputation: 18918

Matlab: Getting a list of vectors

I have a single row matrix theta in Matlab with a couple hundred values; I would like to create a vector for each value in theta. Preferably I can simply store these values in a list so I can take dot products of individual elements in the list lator; how would I go about doing this?

For now, the code I have is

arrayfun(@(x) [sin(x),0,cos(x)],thetas,'UniformOutput',false);

which generates a bunch of [1x3 double]'s.

Upvotes: 2

Views: 1415

Answers (3)

Jonas
Jonas

Reputation: 74940

Instead of creating a cell array, you can also just create a numeric array of size numberOfThetas-by-3, like so:

A = [sin(thetas);zeros(size(thetas));cos(thetas)]'; %'# make n-by-3 by transposing

To calculate the dot product between any two vectors i and j, you can write

dotProduct = sum(A(i,:).*A(j,:));

Upvotes: 3

abcd
abcd

Reputation: 42225

You don't have to unnecessarily construct for loops to re-build the matrix as suggested by strictlyrude27. There is a nice inbuilt function cell2mat that does this for you in a single line.

Say your A is a 100 element cell, each of which holds a 1x3 vector. If you wanted to collect them such that each cell of A is a separate row, the command is simply

matrixA = cell2mat(A(:));

Upvotes: 2

Dang Khoa
Dang Khoa

Reputation: 5823

The output to your code is a cell array, whose elements are the 1x3 vectors you wanted. So suppose you assigned A = arrayfun(@(x) [sin(x),0,cos(x)],thetas,'UniformOutput',false); as you have up there. The vector corresponding with the ith element of array thetas may be accessed with A{i}. At this point you could use a for loop to construct a matrix whose ith column is the vector corresponding to the ith element of thetas.

Upvotes: 1

Related Questions