MATLAB Answers


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?

Asked by Zachary Vexler on 17 Nov 2017
Latest activity Commented on by Star Strider
on 17 Nov 2017
I have a function
if double(x)>95
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
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?


Sign in to comment.



2 Answers

Answer by Star Strider
on 17 Nov 2017

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


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.
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.

Sign in to comment.

Answer by Kelly Kearney
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:
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


Sign in to comment.