Finding the longest row in an array from CSVREAD

조회 수: 4 (최근 30일)
fsgeek
fsgeek 2013년 1월 28일
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!

채택된 답변

Cedric
Cedric 2013년 1월 28일
편집: Cedric 2013년 1월 28일
If your data is stored in array D and is non-zero except for the added elements, one way to obtain the length of each row is the following:
l = size(D,2) - sum(D==0, 2) ;
where l is a column vector of lengths.

추가 답변 (1개)

Image Analyst
Image Analyst 2013년 1월 28일
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.

카테고리

Help CenterFile Exchange에서 Annotations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by