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

조회 수: 1 (최근 30일)
z8080
z8080 2019년 5월 1일
댓글: dpb 2019년 5월 1일
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.

채택된 답변

dpb
dpb 2019년 5월 1일
t=readtable(fileName,'readvariablenames',1);
t.sort=rand(height(t),1);
[~,ix]=sort(t.sort);
t=t(ix,:);
  댓글 수: 4
z8080
z8080 2019년 5월 1일
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
dpb
dpb 2019년 5월 1일
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)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2016a

Community Treasure Hunt

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

Start Hunting!

Translated by