2

I want to add a vector to an existing matrix.

Example:

matrix=[1 2 3 4 5 6 0 7 0] vector = [7 8] 

So the target is to find the equal number of vector and matrix for example with:

ismember(matrix,vector) 

After that the vector should insert into the matrix like the following:

matrix=[1 2 3 4 5 6 0 7 0 0 8 0] 
2
  • I don't understand what you want to achieve. You have a MxN matrix and you want to "insert" a vector where the first element of your vector matches a matrix entry? Waht if there is more than one match? Btw, this sounds like a XY-Problem maybe? Please clarify your question Commented Aug 18, 2017 at 15:03
  • 2
    You should show multiple input output examples if the solution below is insufficient. Commented Aug 18, 2017 at 23:36

1 Answer 1

4

Instead of using ismember, you can better use find with two output arguments:

>> [row, col]=find(matrix==vector(1)) row = 3 col = 2 

Using Matlab's automatic matrix expansion, and assuming the vector is a column vector (you can adjust the code accordingly):

>> matrix(row:(row+length(vector)-1),col) = vector matrix = 1 2 3 4 5 6 0 7 0 0 8 0 

If the match is not at the edge (i.e., row~=size(matrix,1)), this would not work though, as the vector would override other entries.

Sign up to request clarification or add additional context in comments.

3 Comments

You have a idea what i can do if the match is not at the edge? a function to insert the vector and not to override would be nice.
Maybe you should update the problem with a full set of examples of what you're trying to achieve.
@MatthiasR. If this works, consider marking the answer as accepted so this question is shown as closed. Otherwise edit your question to explain why this doesn't answer your question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.