How to get NaN when txt file is not exist

조회 수: 5 (최근 30일)
BENJAMIN BUCHDA
BENJAMIN BUCHDA 2021년 2월 23일
댓글: Walter Roberson 2021년 3월 18일
This is a working function that gets the min, average, max of numbers with a specific row thershold however if i wanted to get an 'NaN' if the txt file or specfic column does not exist, how would I do that?
function res = columnStatistics(fPath, cat, cName)
fConn = fopen(fPath, 'r');
firstLine = fgetl(fConn);
new = [];
while ~feof(fConn)
cLine = fgetl(fConn);
Y = strsplit(firstLine, ',');
X = ismember(Y, cName);
V = find(X);
parts = strsplit(cLine, ',');
O = str2double(parts(V));
tru = strcmp(cat, parts{1});
if (tru)
new(end+1) = O;
else
res = [NaN];
end
end
fclose(fConn);
minData = min(new);
aveData = mean(new);
maxData = max(new);
final = [minData, aveData, maxData];
res = final;
end
  댓글 수: 2
Rik
Rik 2021년 2월 23일
I would encourage you to split the reading of the file and the processing you do with it. That way you can replace code when you need to.
If you want want to set the value NaN if the file doesn't exist, why don't you do that?
And why do you have so many empty lines? And no comments?
Walter Roberson
Walter Roberson 2021년 3월 18일
You posted a question about labeling bars in alphabetic order, but deleted the question before my response made it up.
I post it here as the answer is not obvious.
====
Generalizing it to alphabetic when there was more than 26 possibilities was a bit tricky.
You should consider using categorical data for your x axis.
yData = (randi(9, 1, 30));
W = max(yData);
U = W + 5;
myFig = gcf;
myAx = axes(myFig);
myPlot = bar(myAx, yData);
myPlot.FaceColor = 'flat';
myAx.XTick = 1:length(yData);
myAx.YLim = [0 U];
myAx.Title.String = 'Data Visualization';
myAx.YLabel.String = 'Value';
myAx.XLabel.String = 'Category';
for i = 1:length(yData)
temp = dec2base(i-1,26);
temp(1:end-1) = temp(1:end-1) - 1;
myLab = blanks(length(temp));
mask = temp <= '9';
myLab(mask) = char(temp(mask) - '0' + 'A');
myLab(~mask) = char(temp(~mask) + 10);
myAx.XAxis.TickLabels{i} = myLab;
end

댓글을 달려면 로그인하십시오.

답변 (1개)

Shashank Gupta
Shashank Gupta 2021년 2월 25일
Hey Benjamin,
Check out textscan function, it is useful in the same scenerio as you are interested in. This will help you fill up empty places in the data.
I hope this helps.
Cheers

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by