user3058633
user3058633

Reputation: 91

matlab: how to delete an element from a row vector

I have written a function myMerge which merges two sorted row vectors, this works as it should.

I am now trying to write a new function MergedExp which calls myMerge and then checks to see if any of the elements are the same and if so removes one. for example if I input the two row vectors [1,3,5,6] and [2,5,7,8] myMerge would give [1,2,3,5,5,6,7,8] and i want MergedExp to produce [1,2,3,5,6,7,8] This is what I have so far

function [ answer ] = MergedExp( a,b )
%UNTITLED Summary of this function goes here
%   Detailed explanation goes here

Merge=myMerge(a,b);
l=length(a)+length(b);

for i=1:l-1
    if (Merge(i)==Merge(i+1))
       Merge(i)=[];
    end
end
end

When i remove the semi colons in order to see each step of the function working it does give the answer i'm after but still shows an error message.

Any ideas on how to resolve this would be much appreciated.

Upvotes: 1

Views: 519

Answers (2)

marsei
marsei

Reputation: 7751

The error you have comes from the fact that you loop through the nearly whole vector, 1 to length(vector)-1, but while doing so, you remove some elements. Therefore at some point, the for loop reaches an index that do not correspond to a vector element anymore. And this causes an error.

One of the many solutions to this is store the indexes to remove, and remove them once the for loop is done.

ind_to_remove = [];
for i=1:l-1
  if (Merge(i)==Merge(i+1))
    ind_to_remove = [ind_to_remove i];
  end
end
Merge(ind_to_remove) = [];

Upvotes: 1

Nitish
Nitish

Reputation: 7166

I would recommend using MATLAB's inbuilt function unique.

For instance,

MergedList = [1 2 3 3 3 3 4 5]
MergedList = unique(MergedList)

Output:

MergedList =

     1     2     3     4     5

Upvotes: 1

Related Questions