Ryan Simmons
Ryan Simmons

Reputation: 883

Removing consecutive duplicates from vector MATLAB

Here is my MATLAB code:

[numeric, pics] = xlsread('matrix.xls');
[r,c] = size(pics);
done = r*c;

randvecall = randsample(done, done, true);
randvec = randvecall([1,diff(randvecall)]~=0);
currk = randvec(k);

Essentially what this does is it builds an array of values from a Microsoft Excel spreadsheet. I want to have duplicates in the array, but not consecutive duplicates, so I added a line of code that removes them. When I manually enter values into randvecall and run the above code, it works perfectly. However, when I run the code as seen above, I get the following error:

??? Error using ==> horzcat
CAT arguments dimensions are not consistent.

Error in ==> testAS_randsample at 76
randvec = randvecall([1,diff(randvecall)]~=0);

Why is this happening? For example, this works:

randvecall=[1 2 3 4 5 5 5 5 8 7 8 8];
randvec = randvecall([1,diff(randvecall)]~=0);
disp(randvec)

randvec = [1 2 3 4 5 8 7 8]

That is exactly what I want my code to do. But why does my actual code give me the horzcat error message? Can anybody help me with this? It must have something to do with the way randsample is building the randvecall array, but I can't figure out why this would give me that error message?

Upvotes: 2

Views: 1670

Answers (1)

Luca Geretti
Luca Geretti

Reputation: 10286

That seems to be a problem with how randsample(n,k,true) works: it returns a 1xk vector, while you need a kx1 vector. Transposing randvecall should do the trick.

EDIT:

Let me rephrase it in code for the general reader:

randvec = randvecall([1,diff(randvecall')]~=0);

Upvotes: 3

Related Questions