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 次查看(过去 30 天)
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?

回答(2 个)

Star Strider
Star Strider 2017-11-17
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 个评论
Zachary Vexler
Zachary Vexler 2017-11-17
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 2017-11-17
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
Kelly Kearney 2017-11-17
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)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by