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?
1 view (last 30 days)
Show older comments
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?
0 Comments
Answers (2)
Star Strider
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.
2 Comments
Star Strider
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
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)
0 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!