Matrix Data Results Explanation

1 次查看(过去 30 天)
I have three 5x5 matrices attached here, Lat, Lon, and Data:
I am using the following code:
Lat = [-1 -1 -1 -1 -1;
-2 -2 -2 -2 -2;
-3 -3 -3 -3 -3;
-4 -4 -4 -4 -4;
-5 -5 -5 -5 -5];
Lon = [-50 -40 -30 -20 -10;
-50 -40 -30 -20 -10;
-50 -40 -30 -20 -10;
-50 -40 -30 -20 -10;
-50 -40 -30 -20 -10];
Data = [1 2 3 4 5;
6 7 8 9 10;
11 12 13 14 15;
16 17 18 19 20;
21 22 23 24 25];
intervaloLat = [-3.5, -1.5];
intervaloLon = [-35, -15];
latDentroDoIntervalo = Lat >= intervaloLat(1) & Lat <= intervaloLat(2);
lonDentroDoIntervalo = Lon >= intervaloLon(1) & Lon <= intervaloLon(2);
Resultado = Dados(latDentroDoIntervalo(:,1) & lonDentroDoIntervalo(1,:));
The result of Data should be 2x2: [8, 9; 13, 14]
And it should not be: [8; 13; 9; 14]

采纳的回答

Fangjun Jiang
Fangjun Jiang 2023-9-15
编辑:Fangjun Jiang 2023-9-15
The code looks good and shows good programming flow to use logical index. It will be very lengthy to explain why the result shows in that way. Maybe, if you replace your last line of code with the three lines below, the result would make more sense to you.
You can check the value of every variable after every step to make sense of the size and value of the variable.
Lat = [-1 -1 -1 -1 -1;
-2 -2 -2 -2 -2;
-3 -3 -3 -3 -3;
-4 -4 -4 -4 -4;
-5 -5 -5 -5 -5];
Lon = [-50 -40 -30 -20 -10;
-50 -40 -30 -20 -10;
-50 -40 -30 -20 -10;
-50 -40 -30 -20 -10;
-50 -40 -30 -20 -10];
Data = [1 2 3 4 5;
6 7 8 9 10;
11 12 13 14 15;
16 17 18 19 20;
21 22 23 24 25];
intervaloLat = [-3.5, -1.5];
intervaloLon = [-35, -15];
latDentroDoIntervalo = Lat >= intervaloLat(1) & Lat <= intervaloLat(2)
latDentroDoIntervalo = 5×5 logical array
0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0
lonDentroDoIntervalo = Lon >= intervaloLon(1) & Lon <= intervaloLon(2)
lonDentroDoIntervalo = 5×5 logical array
0 0 1 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 1 0
index=latDentroDoIntervalo & lonDentroDoIntervalo
index = 5×5 logical array
0 0 0 0 0 0 0 1 1 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0
Resultado = zeros(size(Data))
Resultado = 5×5
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Resultado(index)=Data(index)
Resultado = 5×5
0 0 0 0 0 0 0 8 9 0 0 0 13 14 0 0 0 0 0 0 0 0 0 0 0
Or, you can do it this way. This only applies when your "selected area" is "square".
RowIndex=find(all(latDentroDoIntervalo,2))
RowIndex = 2×1
2 3
ColIndex=find(all(lonDentroDoIntervalo,1))
ColIndex = 1×2
3 4
Resultado=Data(RowIndex,ColIndex)
Resultado = 2×2
8 9 13 14

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息

标签

产品


版本

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by