Azzera filtri
Azzera filtri

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

1 visualizzazione (ultimi 30 giorni)
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.

Risposte (1)

Stephen23
Stephen23 il 14 Mar 2018
Modificato: Stephen23 il 14 Mar 2018
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

Categorie

Scopri di più su Multidimensional Arrays in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by