3

If i'm adding a newvlaue to a row vector x, it would be

x = [newvlue, x] % use of ,

but if to a column vector x, it would be

x = [newvlue; x] % use of ;

so i have to know in advance if it's a row or column vector in order to perform this front insertion. But i might not always know as x is meant to be a user inputs. So every time i need to perform this row vector or column vector check beforehand. However, let's say I don't really want to care if it's a row or column vector, I just need to add one element at the front of the array. Is there any elegant way to write the code?

Robert Seifert
  • 25,078
  • 11
  • 68
  • 113
Jeremy
  • 379
  • 2
  • 11

5 Answers5

7

You will have to check for the dimension of the input:

x = [1, 2, 3]
% or
x = [1; 2; 3]
new = 0;

% flexible concatenation
y = cat(~(size(x,1) > 1) + 1, new ,x)

Explanation

d = size(x,1) > 1   % check if column (=1) or row vector (>1)
z = ~(d) + 1        % results in either 1 or 2 for column or row vector
                    % as input for cat
y = cat(z, new ,x)  % concatenate in correct dimension

or by using isrow as suggested in ThomasIsCoding's answer, but I guess it almost does the same:

z = isrow(x) + 1;

In any way you should use isvector to check, whether the input is actually a vector and not a matrix. But actually I would recommend to convert any input, row or column vector, into a column vector with

x = x(:)

to allow for consisting coding within your underlying function.

Robert Seifert
  • 25,078
  • 11
  • 68
  • 113
  • 2
    Most important, the `x = x(:)`. Convert all vectors to a known orientation makes it much easier. – Daniel Apr 14 '20 at 15:09
2

I like one-liners, try this one

a(1:end+1)=[100;a(:)]

works for both row and column matrices.

FangQ
  • 1,444
  • 10
  • 18
2

As @rahnema1 said, just add the new value to the end:

x = flip(x); 
x(end+1) = newvalue; 
x = flip(x);
beaker
  • 16,331
  • 3
  • 32
  • 49
  • You can notice that adding to the end of vector is done with [amortized constant](https://stackoverflow.com/questions/48351041/matlab-adding-array-elements-iteratively-time-behavior) time while concatenation requires reallocation. But your method would be the most efficient answer if flip is done before and after a loop where a high mumber of appendings is performed. – rahnema1 Apr 14 '20 at 22:17
  • @rahnema1 I still think Daniel's and FangQ's answers would be faster, especially if the number of elements to be inserted is known beforehand. – beaker Apr 14 '20 at 22:32
1

Maybe you can define your custom function like below

function y = addhead(x,val)
  if isrow(x)
    y = horzcat(val,x);
  else
    y = vertcat(val,x);
  end
end
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
1

You can use indexing to shift all elements by 1, then insert the new element at the beginning.

x(2:end+1)=x;
x(1)=7;
Daniel
  • 36,610
  • 3
  • 36
  • 69