Trippy
Trippy

Reputation: 213

Adding rows to a matrix matlab

I asked a question earlier regarding a function I'm trying to plot. I wasn't able to get a solution that worked so I'm trying to look at it a different way.

I have a function A which returns to me a 3x1 matrix for an input t and d.

I want to make a 3xn matrix K which has all the possible answers for function A for inputs t and d, in the form 0:1:360 and 0:0.05:0.75 respectively.

So in other words I want to add a new row to the matrix K from the function A which is calculated from the values of t and d.

So for two solutions of A, it would be:

K=[1,2,3;3,4,5] or something along those lines.

How can I make a matrix K like that?

EDIT: Included the function

function [ X ] = type1b(t,d)
%UNTITLED2 Summary of this function goes here
%   Detailed explanation goes here

%Definition of variables (most will be variable)
qr1=[0,0,1]; %Axis of rotation of link 1 (v)
qr2=[0,0,1]; %Axis of rotation of link 2 (v)
H1=[1,0,0]; % Link 1 (v?)
H2=[1,0,0]; % Link 2 (v?)
U1=[cos(t/2),sin(t/2)*qr1]; %quaternion rotor for link 1
U2=[cos(t/2),sin(t/2)*qr2]; %quaternion rotor for link 2
Ug=U1; %Globalising Quaternion (v)


H2g=quatrotate(Ug,H2); %Globalised H2
X=quatrotate(U1,H1)+ quatrotate(U2,H2g)+d;

Upvotes: 0

Views: 126

Answers (2)

bla
bla

Reputation: 26069

To vectorize your function, Just edit the last line of your function to:

X=quatrotate(U1,H1)+ quatrotate(U2,H2g)+repmat(d,[1 3]);

and then you can use

[t d] = ndgrid( 0:360, 0:0.05:0.75);
type1b(t(:),d(:))

Upvotes: 2

Shai
Shai

Reputation: 114786

Assuming function f cannot be vectorized, you can use nested loop:

all_t = 0:1:360;
all_d = 0:.05:.75;
K = zeros( numel(all_t)*numel(all_d), 3 ); % pre allocate - very important
ii = 1;
for t = all_t
    for d = all_d
        K(ii,:) = f( t, d ); % one line
        ii = ii+1;
    end
end

On the other hand, if f can be vectorized, that is accepting several pairs of t and d and returning the corresponding multiple rows of K then this should be more efficient:

[t d] = ndgrid( all_t, all_d );
K = f( t(:), d(:) );

Upvotes: 4

Related Questions