read files and check if something is number

3 ビュー (過去 30 日間)
AIKATERINI KOLIOUKOU
AIKATERINI KOLIOUKOU 2021 年 1 月 12 日
回答済み: Mathieu NOE 2021 年 1 月 13 日
i try to read files line by line
the files are like that : Strength: 438439
B: 489893
C: nothing
D: 832
i want to read the file and as a result i'd like to have Strength=438439 etc. and if i find something that is not a number (like the variable C) an error must appear
how do i check this?

採用された回答

Mathieu NOE
Mathieu NOE 2021 年 1 月 13 日
hello see the different options in code below
my prefered one is the second
a=readcell('test.txt',"Delimiter",":");
% % option 1 : create a structure :
% for ci = 1:size(a,1)
% Varnames{ci} = matlab.lang.makeValidName(a{ci,1});
% myStruct.(Varnames{ci}) = a{ci,2};
% end
% option 2 using assignin (in function variableCreator) :
for ci = 1:size(a,1)
% change blanks in variable names to underscore (otherwise
% variableCreator will throw an error mesage
str = strrep(a{ci,1}, ' ', '_');
val = a{ci,2};
if ischar(val)
disp(['error : non numeric data in line : ' int2str(ci)]);
val = NaN;
end
variableCreator ( str, val )
end
clear str val a ci
% option 3 creating a table - one line engine !
% T = array2table(a)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function variableCreator ( newVar, variable )
assignin ( 'caller', newVar, variable );
end

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeWhos についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by