Finding a specific rows?
Ältere Kommentare anzeigen
I have this Matrix:
m = [0 0 0 0 0 0 0 0
0 3.410 0 0 0 0 0 0
10.83 11.87 7.240 3.470 1.610 1.610 0 0
20.99 18.23 17.72 6.010 3.790 3.790 1.100 0
25.26 20.40 22.70 7.590 6.990 6.990 1.550 0
22.86 19.13 24.48 8.280 9.240 9.240 2.180 0
14.92 15.73 23.19 8.280 11.61 11.61 2.690 0
10.83 11.87 22.18 8.280 12.79 12.79 3.010 0
9.050 10.69 22.70 8.490 14.91 14.91 3.500 0
9.840 11.19 23.75 8.490 16.02 16.02 3.790 0
9.840 11.54 24.48 8.840 16.43 16.43 4.100 0
8.070 10.20 25.18 9.180 17.73 17.73 4.750 0
5.230 8.350 24.48 9.180 19.28 19.28 5.800 0
3.680 6.630 25.18 8.840 22.49 22.49 6.980 2.190
0 3.190 22.70 7.840 28.06 28.06 8.280 3.320
0 0 13.03 6.010 34.68 34.68 10.88 5
0 0 0 3.470 32.87 32.87 13.86 5.300
0 0 0 0 15.14 15.14 12.27 0
0 0 0 0 1.240 1.240 1.450 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
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 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 0 0 0 0 0 0
0 0 0 0 0 0 0 0
40.53 25 0 0 0 0 0 0]
% * Edited by Adam Danz to allow for copy-pasting into command window
I want to find the first row where all the columns have a value below 10. How to do this? I have made an if statement, but this seems to specific and I was wondering if there would be another way.
Akzeptierte Antwort
Weitere Antworten (1)
Mario Chiappelli
am 18 Jul. 2019
Bearbeitet: Mario Chiappelli
am 18 Jul. 2019
I would use a double nested For statement and a counter variable as follows:
for i = 1:31 % Number of rows
counter = 0; % Reset the counter
for j = 1:8 % Number of columns
if myMatrix(i,j) < 10
counter += 1;
end
if counter == 8 % In other words when all values are under 10
disp("Row ");
disp(i);
disp(" only contains numbers less than 10");
end
end
end
If you want it to stop after the first row is detected just add a series of break statements to break out of the for loop in the if statement that checks if the counter is equal to 8
If your matrix changes sizes over the course of the program, you are going to have to assgin the dimensions of the matrix to variables and use those as your for statement parameters.
Hope this helps :)
1 Kommentar
Adam Danz
am 18 Jul. 2019
Have you tried to run this? There are several errors.
- counter += 1; I think you mean counter = counter + 1;
- if myMatrix(i,j) < 10 this might work for the example given but if the dimensions of myMatrix ever changes, this might break.
- Same with i = 1:31 and j = 1:8 and counter == 8
Even after correction those errors, the algorithm doesn't work for this example matrix:
myMatrix =
0 0 0 10 10
10 10 0 0 0
0 0 0 0 0
Kategorien
Mehr zu Introduction to Installation and Licensing finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!