Borrar filtros
Borrar filtros

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

1 visualización (últimos 30 días)
Lodewijk Pleij
Lodewijk Pleij el 14 de Mzo. de 2018
Editada: Stephen23 el 14 de Mzo. de 2018
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.

Respuestas (1)

Stephen23
Stephen23 el 14 de Mzo. de 2018
Editada: Stephen23 el 14 de Mzo. de 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

Categorías

Más información sobre Multidimensional Arrays en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by