Finding the longest row in an array from CSVREAD
4 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Hey guys,
I've read in a text file from csvread. The text file was something like this:
1, 1, 1, 1, 1
2, 2, 2, 2, 2, 2, 2, 2, 2, 2
3, 3, 3, 3, 3, 3, 3
After reading it in with csvread, I get the array:
1, 1, 1, 1, 1, 0, 0, 0, 0, 0
2, 2, 2, 2, 2, 2, 2, 2, 2, 2
3, 3, 3, 3, 3, 3, 3, 0, 0, 0
The only problem with this is that I want to be able to determine the length of each row excluding the zeros that have automatically been appended in order to keep the matrix square.
The significance of my problem is that these number represent a stress signal and I need to count the cycles in each signal. There are only 5 cycles in the first row, but simply taking
[cycles, ~] = size(matrix);
Will return 10 cycles because it includes the zeros after the 1s. This is bad because when my code performs a damage calculation on the signal it will count 10 cycles every time when it should only could 5, 10 and 7 cycles.
Is there a way of being able to determine the length of each signal so that I get the correct values i.e. 5, 10 and 7 for the aforementioned text file?
Thanks!
0 Commenti
Risposta accettata
Più risposte (1)
Image Analyst
il 28 Gen 2013
Try this to find the length of each row and record which row is longest, plus the length of the longest row:
% Sample data.
M = [...
1, 1, 1, 1, 1, 0, 0, 0, 0, 0
2, 2, 2, 2, 2, 2, 2, 2, 2, 2
3, 3, 3, 3, 3, 3, 3, 0, 0, 0]
% Find rectangular size.
[rows, columns] = size(M);
% Initialize the parameters we want to find.
longestRow = 0;
lengthOfLongestRow = 0;
for row = 1 : rows % Loop over all rows
% Get length of this row
lengthOfThisRow = find(M(row,:)==0, 1, 'first')
% If it's the longest row, save its parameters.
if lengthOfThisRow > lengthOfLongestRow
longestRow = row;
lengthOfLongestRow = lengthOfThisRow;
end
end
% Tell user what we found.
fprintf('The longest row is row #%d with a length of %d\n',...
longestRow, lengthOfLongestRow);
In the command window:
M =
1 1 1 1 1 0 0 0 0 0
2 2 2 2 2 2 2 2 2 2
3 3 3 3 3 3 3 0 0 0
lengthOfThisRow =
6
lengthOfThisRow =
Empty matrix: 1-by-0
lengthOfThisRow =
8
The longest row is row #3 with a length of 8
Note, this assumes you won't have any zeros in the middle of your "good" data. Otherwise you'll have to reverse your row with fliplr() and look for the last zero with find(fliplr(M(row,:))==0, 1, 'last'), then adjust the length appropriately.
0 Commenti
Vedere anche
Categorie
Scopri di più su Cell 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!