Hi there,
I have a 4 columns .csv file. I want to create an matrix of only the SECOND And FOURTH columns
How do I do this?
Thanks!

回答 (1 件)

Walter Roberson
Walter Roberson 2019 年 4 月 3 日
編集済み: Walter Roberson 2019 年 4 月 3 日

0 投票

filename = 'BlackModelTest.csv';
[fid, msg] = fopen(filename, 'rt');
if fid < 0
error('Could not open file "filename" because: "%s"', filename, msg);
end
col2 = {};
col4 = {};
while true
thisline = fgetl(fid);
if ~ischar(thisline); break; end %normal: indicates end of file
if isempty(thisline); continue; end %empty line, including possibly just before end of file
fields = regexp(thisline, ',', 'split');
if length(fields) >= 2
col2{end+1} = fields{2};
end
if length(fields) >= 4
col4{end+1} = fields{4};
end
end
fclose(fid);
temp = str2double(col2);
if ~any(isnan(temp))
col2 = temp; %convert to double if ALL entries can be converted
end
temp = str2double(col4);
if ~any(isnan(temp))
col4 = temp; %convert to double if ALL entries can be converted
end
You will now have variables col2 and col4. If the columns contained only numeric values, then the corresponding variable will be numeric; otherwise it will be a cell array of character vectors. This code does not try to figure out whether there were header lines.
This code does not assume that all lines are complete or that all lines are the same number of fields. Extra fields will be ignored. If the line is too short then the empty array will be at that location.

7 件のコメント

Megan Stapley
Megan Stapley 2019 年 4 月 3 日
編集済み: Megan Stapley 2019 年 4 月 3 日
How do I get col2 and col4 into ONE MATRIX?
Megan Stapley
Megan Stapley 2019 年 4 月 3 日
All I want to see in my output is this: How do I achieve that? None of your solutions have worked thus far.Screen Shot 2019-04-03 at 3.55.29 PM.png
Walter Roberson
Walter Roberson 2019 年 4 月 3 日
{col2(:), col4(:)}
Megan Stapley
Megan Stapley 2019 年 4 月 3 日
Didn't work...output:
final =
1×2 cell array
{21×1 cell} {21×1 cell}
Walter Roberson
Walter Roberson 2019 年 4 月 3 日
[col2, col4]
Megan Stapley
Megan Stapley 2019 年 4 月 3 日
That outputs a 1 X 42 array
Not a 2 column matrix
Walter Roberson
Walter Roberson 2019 年 4 月 3 日
[col2(:), col4(:)]

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

カテゴリ

ヘルプ センター および File ExchangeCell Arrays についてさらに検索

製品

リリース

R2016b

タグ

質問済み:

2019 年 4 月 3 日

コメント済み:

2019 年 4 月 3 日

Community Treasure Hunt

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

Start Hunting!

Translated by