问题
I am new to MATLAB. I have a data structure named da
. I want to sort the first column of da.mat
and want to let da.rid
and the other columns to follow the rearranged order. da.cid
contains the column names and da.rid
contains the row IDs.
da =
mat: [22268x377 single]
rid: {22268x1 cell}
rhd: {''}
rdesc: {22268x1 cell}
cid: {377x1 cell}
chd: {0x1 cell}
cdesc: {377x0 cell}
Also, if I want to use some other column instead of the first column of da.mat
and which I will get from da.cid
, how can I acheive it?
For example, if I want to look for the column name 'A02'
in cid
and use it to select the specific column of da.mat
for sorting. Could you please help me? Thanks.
Woody
回答1:
Assuming by other columns, you mean other columns of da.mat
itself, you may try this -
[val,ind] = sort(da.mat(:,1))
da.mat = da.mat(ind,:)
da.rid = da.rid(ind)
If you are looking to use some other column number instead of 1
for sorting and based on the names in the field cid
, use this -
cid_matchcol = 'A02'; %// column name to be used from `da.cid` to choose column of `da.mat`
base_col = find(strcmp(da.cid,cid_matchcol),1)
[val,ind] = sort(da.mat(:,base_col))
da.mat = da.mat(ind,:)
da.rid = da.rid(ind)
来源:https://stackoverflow.com/questions/23668450/matlab-how-to-sort-a-matrix-by-a-specific-column-name-and-also-let-the-row-name