Data with different length of rows

3 ビュー (過去 30 日間)
Sara Boznik
Sara Boznik 2020 年 8 月 26 日
コメント済み: Star Strider 2020 年 8 月 26 日
Hi
I have following question. I have data like this:
1 2 3 4 5 6 7 8 9
1 2 3 4
1 2
I want to calculate average of each row.
I have following code:
row=load('file.txt')
n=length(row(:,1))
[n,m]=size(row)
for i=1:n
avg(i)=mean(row(i,:))
end
Unfornatelly does not work, I got the error:
Unable to read file 'filei.txt'. Input must be a MAT-file or an ASCII file containing numeric data with
same number of columns in each row.
I have no idea what to do, do you have any advice?
Any help is aprriciated.

採用された回答

Star Strider
Star Strider 2020 年 8 月 26 日
Try this:
fidi = fopen('file.txt','rt');
k = 1;
while ~feof(fidi)
row = fgetl(fidi);
avg(k,:) = mean(str2num(row));
k = k+1;
end
fclose(fidi);
With:
RowMeans = avg
producing:
RowMeans =
5.0000
2.5000
1.5000
.
  2 件のコメント
Sara Boznik
Sara Boznik 2020 年 8 月 26 日
Thank you so much, that works.
Star Strider
Star Strider 2020 年 8 月 26 日
As always, my pleasure!
A better option would be str2double rather than str2num. I thought of that later. (The result would not change.)

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by