Search code examples
matlabvectorsplice

How do I splice two vectors in MATLAB?


I need to splice two vectors based on a condition that also takes a vector as an argument. Example:

vec_cond = -5:5;       % The exact values are calculated differently
vec1     = 0:10;
vec2     = 5:15;

I need a resulting vector to be comprised from values out of both vectors based on a condition from the third vector. Let's assume this is the condition: vec_cond >= 0

Then if this is true, I want vec_result to have values from vec1 on appropriate indexes, and if not, take values from vec2 on appropriate indexes:

vec_result = vec1 if (vec_cond >=0) else vec2

This is portion of my MATLAB script (original comments were Czech) where I would need to use that:

%% Draw output current and voltage characteristics
R       = 100:5:2*10^3;             % Load rezistor          [ohm]
U_2     = R .* (I * 10^(-3));       % Load voltage             [V]
U_1stab = U_LM + U_x + U_2;         % Min. required input voltage
                                    % for stabilization        [V]
U_delta = U_1 - U_1stab;            % Difference between actual and
                                    % min. req. input voltage  [V]
U_2norm = U_1 - U_LM - U_x          % Calculating output load
                                    % voltage based on params  [V]

I_z     = U_2norm ./ R .* 10^3;     % Load current param based[mA]
I_r1    = I * I_z.^0;               % Stabilizator current    [mA]

So the condition would be U_delta >= 0.

I tried to use a ternary operator, which I found here:

I_graph = (U_delta >= 0) : (@() I) : (@() I_z);         % Current splice  [mA]
U_graph = (U_delta >= 0) : (@() U_2) : (@() U_2norm);   % Voltage splice   [V]

That means that for I_graph, if the condition is met, take a constant value I and vectorize it, otherwise take values from I_z vector. For U_graph, if the condition is met, take values from U_2 vector, otherwise take constant value of U_2norm and vectorize it.

But it didn't work, this is what it tells me:

Operator ':' is not supported for operands of type 'function_handle'.

Error in vypocet1 (line 52)
I_graph = (U_delta >= 0) : (@() I) : (@() I_z);         % Current splice  [mA]

I guess that I might want to use for loop, but I'm not sure how it will help me and how can I actually construct the necessary vector using a for loop.


Solution

  • Given:

    vec_cond = -5:5;
    vec1     = 0:10;
    vec2     = 5:15;
    

    You can set:

    out = vec2;
    I = vec_cond >= 0;
    out(I) = vec1(I);
    

    This uses logical indexing, which is indexing with a logical array.

    By the way, the ternary operator you found is an exercise to overload the : operator for a specific class to do something that it normally doesn’t do. Note how you use the colon when creating vec_cond. This is what the colon operator does normally.