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 Center および File ExchangeCell Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by