MATLAB Answers

Translated by

이 페이지의 내용은 영어에서 자동 번역되었습니다. 자동 번역 기능을 해제하려면 "<a class="turn_off_mt" href="#" onclick="window._kiq.push(['set', { 'event': 'Turn off MT' }]);">여기</a>"를 클릭하십시오.

0

Sorting a mixed text-numeric matrix (cell array) by one of its (numeric) columns

Asked by z8080 on 1 May 2019
Latest activity Commented on by dpb
on 1 May 2019
Accepted Answer by dpb
I have an Excel spreadsheet whose rows I'd like to randomly shuffle and further use in Matlab. To that end, I'm reading the XLS into a cell array, generating random numbers into a column, then sorting by that column. This is proving to be problematic though, because of conflicting variable types. The code I used is:
[num, txt, M] = xlsread(fileName);
for row=2:row_N % generate random numbers in the D column
M(row,4) = num2cell(rand);
end
M = sortrows(M,4);
This leads to my matrix looking like this:
01-05-2019 13.39.09.jpg
Because the D column contains numbers while there's text in the other columns, the sorting cannot be done (it says "Cell elements must be character arrays.").
I tried various conversions between numeric and cell variables, and also tried using 'readtable' instead of 'xlsread' - but there is always a problem, such that I cannot get this conflict solved.

  0 Comments

Sign in to comment.

Products


Release

R2016a

1 Answers

Answer by dpb
on 1 May 2019
 Accepted Answer

t=readtable(fileName,'readvariablenames',1);
t.sort=rand(height(t),1);
[~,ix]=sort(t.sort);
t=t(ix,:);

  4 Comments

'1' is "True" -- unless TMW has broken backwards compatibility and now on a later release is actually type-checking??? Let's hope not; a LOT of code is going to break, including TMW's own...
I'd have thought 1 would work as well, but I got an error which went away when I replaced with true.. no matter, the solution proposed is very good, thanks again
Ah!
Did you use 1 or '1' ? It's a numeric one, not character (altho T==>~0 so should still be ok altho I can see a test for other than logical or numeric)

Sign in to comment.



Translated by