A declared class of variable is ignored. Why?

1 回表示 (過去 30 日間)
Feld
Feld 2020 年 6 月 21 日
コメント済み: Feld 2020 年 6 月 22 日
I am trying to scan data from a .csv file using textscan in a for loop. When undeclared, the variable is a complicated multidimensional array. So tried to declare the class of the data variable before the loop, but it was ignored. It worked on another computer, so I'm not sure where the problem is. is it a problem with matlab?
How can i stop matlab from igmoring the declaration of the variable?
f = fopen(filename);
line = fgetl(f);
i = 1;
data = struct.empty;
while ischar(line)
data{i,1} = textscan(line, '%s', 'delimiter', ';' );
line = fgetl(f);
i = i+1;
end
  2 件のコメント
Stephen23
Stephen23 2020 年 6 月 21 日
編集済み: Stephen23 2020 年 6 月 22 日
Like all array elements, structure elements are accessed using parentheses, so it is unlikely that this indexing does anything useful for your code:
data{i,1} = ...
The correct indexing for structure arrays is shown in the documentation:
I guess that your code implicitly replaces the structure with a cell array, but I have not tested this to confirm.
Curly braces are used to access the contents of container arrays, e.g. the contents of a cell, a table, or a string.
Feld
Feld 2020 年 6 月 22 日
Yes, that is a mistake, thank you. When I used parentheses instead of the curly brackets, a plot popped up and I have no idea why...

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

回答 (1 件)

Walter Roberson
Walter Roberson 2020 年 6 月 22 日
S = fileread(filename);
lines = regexp(S, '\r?\n', 'split');
if isempty(lines{end}); lines(end) = []; end %trailing empty line
data = regexp(lines, ';', 'split');
data will now be a cell array with one entry for each line, and the entry will be a cell array of character vectors divided at each ';' character.
If the number of ';' is the same on every line, there is typically a better representation.

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by