【发布时间】:2015-05-13 03:20:33
【问题描述】:
我有下面的代码用于对两个向量进行相反排序。它有效,但我想指定行
B_diff(i) = B(i) - B(i+1);
坚持不只是为了
B_diff(i) = B(i) - B(i+1); 但对于
B_diff(i) = B(i) - B(i+k); 其中 k 可以是小于或等于 n 的任何整数。这同样适用于“A”。关于我如何在程序中实现这一点的任何线索?
比如我想重新排列矩阵的第一列
A =
1 4
6 9
3 8
4 2
这样,条件不仅应该成立
(a11-a12)(a21-a22)<=0;
但也适用于所有人
(a11-a13)(a21-a23)<=0;
(a11-a14)(a21-a24)<=0;
(a12-a13)(a22-a23)<=0;
(a12-a14)(a22-a24)<=0; and
(a13-a14)(a23-a24)<=0;
## MATLAB CODE ##
A = xlsread('column 1');
B = xlsread('column 2');
n = numel(A);
B_diff = zeros(n-1,1); %Vector to contain the differences between the elements of B
count_pos = 0; %To count the number of positive entries in B_diff
for i = 1:n-1
B_diff(i) = B(i) - B(i+1);
if B_diff(i) > 0
count_pos = count_pos + 1;
end
end
A_desc = sort(A,'descend'); %Sort the vector A in descending order
if count_pos > 0 %If B_diff contains positive entries, divide A_desc into two vectors
A_less = A_desc(count_pos+1:n);
A_great = sort(A_desc(1:count_pos),'ascend');
A_new = zeros(n,1); %To contain the sorted elements of A
else
A_new = A_desc; %This is then the sorted elements of A
end
if count_pos > 0
A_new(1) = A_less(1);
j = 2; %To keep track of the index for A_less
k = 1; %To keep track of the index for A_great
for i = 1:n-1
if B_diff(i) <= 0
A_new(i+1) = A_less(j);
j = j + 1;
else
A_new(i+1) = A_great(k);
k = k + 1;
end
end
end
A_diff = zeros(n-1,1);
for i = 1:n-1
A_diff(i) = A_new(i) - A_new(i+1);
end
diff = [A_diff B_diff]
prod = A_diff.*B_diff
【问题讨论】:
-
给定样本输入数据的预期输出必须是什么?
-
应该是这样的 A = 3 4 1 9 4 8 6 2 第一列被打乱,而第二列保持不变
-
如果我假设:
a11作为 A 的col-1,row-1,a12作为 A 的col-1,row-2,a21作为 A 的col-2,row-1,...a24作为 @ A的987654335@,其中A是双列输入数据,看不出预期的输出,A = [3 4; 1 9; 4 8 ;6 2]如何满足(a11-a13)(a21-a23)<=0;的第二个条件
标签: matlab