## I'm trying to sort one vector based on another vector of seemingly the same size, but i keep getting the index exceeds matrix dimensions error. What's the issue?

### Zachary Vexler (view profile)

on 17 Nov 2017
Latest activity Commented on by Star Strider

### Star Strider (view profile)

on 17 Nov 2017
I have a function
function[y,z]=capital(x)
if double(x)>95
y=2*double(x)-63;
else
y=2*double(x);
z=int8(y);
end
that i'm using to give values to characters alphabetically and by capitalization. I have gene='AbcDaBCd', so capital(gene) is [130 196 198 136 194 132 134 200]. I'm sorting gene with
[~,capsort]=sort(capital(gene))
capsort(gene)
The sorting is giving me the error. I've tried instead of gene int8(gene) and that doesn't work either. What am i missing here?

### Products ### Star Strider (view profile)

on 17 Nov 2017

One approach:
gene='AbcDaBCd';
caps = regexp(gene, '[A-Z]');
v = sort(gene(caps));
I can find no reference to the capital function in the online documentation.

Zachary Vexler

### Zachary Vexler (view profile)

on 17 Nov 2017
capital is the function that I defined at the top. Capital(gene) can be sorted just fine, I just don't understand why it's saying index exceeds matrix when gene and capital(gene) both have 8 elements.
Star Strider

### Star Strider (view profile)

on 17 Nov 2017
If ‘capital(gene)’ has only eight elements, none of the subscripts should be greater than eight.
My regexp call provides the correct subscripts that you can then sort however you wish.
Your function returns the ASCII values of the argument. Those are not the same as the subscripts.
You may want something like this:
capital = @(g) find(ismember(double(g),double(['A':'Z'])));
Result = gene(sort(capital(gene)))
The regexp call is easier. I don’t know if it’s faster, since I didn’t time it.

### Kelly Kearney (view profile)

on 17 Nov 2017

I'm pretty sure there a couple things in here that aren't working like you'd like them to.
First, in you capital function, the statement:
if double(x)>95
translates as
if (all(double(x)>95)
because that's how the if statement handles vectors. It does not implicitly loop over vectors. So your strings are not getting capitalized (unless they were all capital to begin with, which is redundant). The following is the vectorized way to do things:
function[y,z]=capital(x)
y = 2 * double(x);
y(x > 95) = y(x > 95) - 63;
z = int8(y);
But really, why reinvent the wheel? Matlab already has a capitalization function:
y = upper(gene);
z = int8(y);
Your error, however, is due to you reversing the use of variable and indices in your last statement. The capsort variable returns a list of indices, not a function. You're then requesting capsort(gene) = |capsort(double(gene)) = capsort([65 98 99 68 97 66 67 100]). Instead, you want
gene(capsort)