Sort Descend Scientific Notation Error
显示 更早的评论
Hi,
I've got a vector of numbers. The vector has some numbers stored with and without scientific notation.
Eg 0.01 and 9.8e-04.
When i try sorting these numbers in descending order, the sort function puts 9.8e-05 above 0.01, even though 0.01 is larger.
Can anyone help me so it sorts from largest to smallest based on the expanded values? I've been trying to convert the numbers in the matrix from scientific notation to standard form, but changing format has not helped, and i haven't been able to get rid of the scientific notation properly.
I've looked through past questions / answers and have not found an answer that has worked for me.
Any advice is appreciated.
I believe the issue may be that the numbers are considered strings, but unsure how to convert string scientific notation to numbers.
Example data and code:
u =
[ APH 0.01
GPT 9.8e-04
CPH 6.4e-05]
[~,idx] = sort(u(:,2),'descend');
sortedu = u(idx,:);
sortedu looks like:
sortedu =
[GPT 9.8e-04
CPH 6.4e-05
APH 0.01]
Thanks,
Kiran
edit: updated code.
4 个评论
Not much of your code makes sense. The row vector u is defined like this (so far no problems):
u = [ 0.01 9.8e-04 6.4e-05 ];
but then you use indexing to take only the second column, which is a scalar:
>> u(:,2)
ans = 0.00098000
You then sort that scalar, where obviously the sort index of a scalar is one (and it makes absolutely no difference using 'ascend' or 'descend'), and this is easy to confirm:
>> [~,idx] = sort(u(:,2))
idx = 1
You then use the index 1 to select the first row of u. I guess you thought that your code did some sorting and that idx would change the order. In fact your code is simply equivalent to:
sortedu = u(1,:)
which because u is a row vector anyway is simply
sortedu = u
This is not the output that you showed us, which means that you did not actually give us the data and/or code that you used. If you do not show us what you are actually doing, then you make it hard for us to help you.
My suspicion is that you actually have a string array, not a numeric array as you showed us.
Kiran Eswaran
2019-10-14
Kiran Eswaran
2019-10-14
编辑:Kiran Eswaran
2019-10-14
Stephen23
2019-10-15
@Kiran Eswaran : please upload your original data in a .mat file, by clicking the paperclip button. Note that I wrote "original data": this means your original table u (or whatever it is called), before you tried to do any conversions.
回答(1 个)
Jos (10584)
2019-10-14
编辑:Jos (10584)
2019-10-14
You misuse the sort command. Simply:
sortedu = sort(u ,'descend')
would do :-)
Moreover, if you remove the semicolons, you would see that you have some strange results in between...
Ask yourself what u(:,2) does, and u(idx,:).
类别
在 帮助中心 和 File Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!