Swapping numbers of two arrays when one is greater than the other

1 次查看(过去 30 天)
I have two arrays of numbers 'Length' and 'Width'. These are the lengths and widths of pieces of grains. So the first number of both is the length and width of the first grain, second length and width from the second grain and so on. I have 60 grains, so the arrays are both 60x1. The problem is that the width should always be longer than the length. So when the width is smaller than the length, I would like my code to swap that number with the according length so that the width is always longer than the length. I have came this far:
for i=1:60;
if Length(i)>Width(i);
Length(i)=Width(i);
end
end
The problem is that the code now enters the width at the position of the length, but not the other way around. How do I fix this? Thank you in advance.

回答(1 个)

Stephen23
Stephen23 2018-3-14
编辑:Stephen23 2018-3-14
This is MATLAB, so loops and if's are not required:
>> Length = [1;5;7];
>> Width = [3;6;4];
>> tmp = sort([Length,Width],2);
>> Length = tmp(:,1)
Length =
1
5
4
>> Width = tmp(:,2)
Width =
3
6
7

类别

Help CenterFile Exchange 中查找有关 Multidimensional Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by