필터 지우기
필터 지우기

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

조회 수: 2 (최근 30일)
Lodewijk Pleij
Lodewijk Pleij 2018년 3월 14일
편집: Stephen23 2018년 3월 14일
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