Another way to do what strsplit does

Hello.
What I am looking for is a way to do what strsplit does since my teacher said he didn't know this function and therefore i could not use it. My code so far is
function [n_nos, graph] = Receber1( fich )
f = fopen(fich, 'r');
if f == -1
disp('Insucesso ao abrir o ficheiro.');
else
n_nos = 0;
graph = [];
while feof(f) == 0
line = fgetl(f);
graph(end+1, :) = str2double(strsplit(strtrim(line)));
n_nos = n_nos+1;
end
fechar = fclose(f);
if fechar == 0
disp('Ficheiro carregado com sucesso.');
else
disp('Insucesso ao fechar o ficheiro.');
n_nos = -1;
end
end
end
Thank you so much.

3 件のコメント

David Barry
David Barry 2016 年 12 月 17 日
What a terrible teacher! I suggest he goes back to school. Has he told you what functions he does know and thus you are allowed to use?
Jan
Jan 2016 年 12 月 17 日
Tell your teacher:
doc strsplit
Sofia Batista
Sofia Batista 2016 年 12 月 17 日
Indeed!! I am very restrained because of him and my code is working perfectly but i can't use it.

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

 採用された回答

Jan
Jan 2016 年 12 月 17 日
編集済み: Jan 2016 年 12 月 17 日

0 投票

The str2double(strsplit(strtrim(.))) is an overkill here, when a simple sscanf does the same already:
function [n_nos, graph] = Receber1( fich )
f = fopen(fich, 'r');
if f == -1 % IMPORTANT: Stop with an error
error('Insucesso ao abrir o ficheiro: %s', fich);
end
n_nos = 0;
graph = [];
while feof(f) == 0
line = fgetl(f);
graph(end+1, :) = sscanf(line, '%f').'; [EDITED]
n_nos = n_nos+1;
end
fclose(f); % No test required
end
If the opening of the file fails, stopping with an error is the only secure reaction. Returning without defining the outputs will produce a strange and confusing error message instead.
General rule: Let the code stop in case of an error to avoid running the program in an undefined state with potentially unpredictable effects.
Closing the file can fail under extremely rare conditions only and will not produce any harm. Only if this happens about 250 times, Matlab cannot open files anymore, but this is detected by checking the -1 after fopen already.

3 件のコメント

Sofia Batista
Sofia Batista 2016 年 12 月 17 日
Hello.
It's actually de perfet way to do it! But it returns
Subscripted assignment dimension mismatch.
Error in Receber1 (line 10)
graph(end+1, :) = sscanf('%f', line).';
What could i do to change this?
Jan
Jan 2016 年 12 月 17 日
編集済み: Jan 2016 年 12 月 17 日
A typo: sscanf(line, '%f') instead of sscanf('%f', line). See the [EDITED] line.
Sofia Batista
Sofia Batista 2016 年 12 月 17 日
Thank you !!! It's perfect!

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeDates and Time についてさらに検索

質問済み:

2016 年 12 月 17 日

編集済み:

2016 年 12 月 17 日

Community Treasure Hunt

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

Start Hunting!

Translated by