sorting a matrix of 4 rows by the fourth element and outputting of combinations that make the 4th row element
3 次查看(过去 30 天)
显示 更早的评论
My project so far has been to create a vector of numbers:
%x: a vector of numbers
x = 1:4;
and then create a 3 column matrix of the all the possible combinations of the vector x
%n: number of elements to pick (with repetetition) from x. n must be less than or equal to numel(x)
n = 3;
assert(n < numel(x), 'n can''t be greater than numel(x)')
combs = cell(1, n);
[combs{:}] = ndgrid(x);
combs = reshape(cat(n+1, combs{:}), [], n); %a numel(x)^n X n matrix of combinations
and add a 4th column to the matrix which is the energy of the the 3 columns which is equal
length = length(combs);
for x=1:length
combs(x,4) = combs(x, 1)^2+combs(x, 2)^2+combs(x, 3)^2;
E(x,:) = combs(x,4);
end
This produces a matrix similiar to the picture below:
This code works great but I want to re oragnize the rows according to the energy (4th) column to look like this:
So the rows will start with 4th column is 3 and then the next three are 6, and so fourth. I'm not sure how to do this, and would appreciate any help. Just a FYI I plan to change the vector from 4 to 14, this simulation is for Griffth's Quantum mechanics problem 4.2.B, I already know the answer but I figured it would be a fun to see the matrix blow up as well as practice coding. I remember doing something similiar in Java but its been a long time ago.
Thank you,
-Leo Q
0 个评论
采纳的回答
KSSV
2021-7-22
NOTE: Never use a function name as the variable. You have used length as variable, this is problematic.
clc; clear all ;
%x: a vector of numbers
x = 1:4;
%n: number of elements to pick (with repetetition) from x. n must be less than or equal to numel(x)
n = 3;
assert(n < numel(x), 'n can''t be greater than numel(x)')
combs = cell(1, n);
[combs{:}] = ndgrid(x);
combs = reshape(cat(n+1, combs{:}), [], n); %a numel(x)^n X n matrix of combinations
thelength = length(combs);
for x=1:thelength
combs(x,4) = combs(x, 1)^2+combs(x, 2)^2+combs(x, 3)^2;
E(x,:) = combs(x,4);
end
%% Arrange combs
v = combs(:,end) ;
[c,ia,ib] = unique(v) ;
iwant = cell(length(c),1) ;
for i = 1:length(c)
iwant{i} = combs(ib==i,:) ;
end
celldisp(iwant)
更多回答(1 个)
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!