How to reorder columns and array elements based on an array?
14 次查看(过去 30 天)
显示 更早的评论
I'm working with a 1000x20 matrix containing weight measurements of 20 different species, ordered alphabetically. I want to plot mean weight measurements 1) separately for each species (so 20 elements), and 2) grouped based on various characteristics, like the biome (so 2-4 elements).
I created a 1x20 string with all species names (used in tick labels), and then arrays with column indices corresponding to various species, like this:
all_species = 1:20;
species_groups.biome1 = [5 6 8 10 11 12 16]; % species in biome 1
species_groups.biome2 = setdiff(all_species,species_groups.biome1); % species in biome 2
This way, I'm able to easily define input data for various figures and plot the mean weight of whichever species I want.
Now I want to change the order of species in the figure where each species is plotted separately - or preferably, in the entire dataset before any analysis is done. I have a new 1x20 string with the desired order:
new_order = [14 13 15 12 16 4 3 5 6 8 9 7 1 2 17 18 19 20 10 11];
What's the easiest way to:
1) reorder the columns in my original 1000x20 dataset based on this array, so that e.g. the species that was 14th in the original dataset would instead come first?
2) Replace all the numbers (in fact column indices) in species_groups with corresponding values from the new_order array?
Many thanks in advance for help!
0 个评论
采纳的回答
Dyuman Joshi
2024-2-21
"1) reorder the columns in my original 1000x20 dataset based on this array, so that e.g. the species that was 14th in the original dataset would instead come first?"
Directly use those indices -
all_species = 1:20;
species_groups.biome1 = [5 6 8 10 11 12 16]; % species in biome 1
species_groups.biome2 = setdiff(all_species,species_groups.biome1); % species in biome 2
species_groups
new_order = [14 13 15 12 16 4 3 5 6 8 9 7 1 2 17 18 19 20 10 11];
data = data(:,new_order);
"2) Replace all the numbers (in fact column indices) in species_groups with corresponding values from the new_order array?"
Once again, indexing ftw -
species_groups.biome1 = new_order(species_groups.biome1); % species in biome 1
species_groups.biome2 = new_order(species_groups.biome2); % species in biome 2
species_groups
5 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Distribution Plots 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!