Question

I have a number of files, while some are empty, but when looping until the empty, then it return me the error. How to avoid this case and return 0 when there is nothing in the file. Here is my code, I want both of the condition to meet, check whether ' A27_data' got inside 'data2', while some of the 'data2' files are empty.

data2 = importdata(strcat('f9data\','f7_data', int2str(i)));
feature27_data=(cellfun(@(n) ~isempty(n), strfind(data2, A27_data)))

enter image description here

Here are my full code, I have do checking for the empty file.

data = importdata('DATA/URL/testing_URL')

domain_URL = regexp(data,'\w*://[^/]*','match','once')

[sizeData b] = size(domain_URL);

for i = 1:5

A27_data = domain_URL{i};

s =dir(strcat('f9data\','f7_data', int2str(i)));
if s.bytes == 0
    return 0;
else
    data2 = importdata(strcat('f9data\','f7_data', int2str(i)));
end;

feature27_data=(cellfun(@(n) ~isempty(n), strfind(data2, A27_data)))

B27(i)=sum(feature27_data)
end

feature27(B27>=10)=1;
feature27(B27<10&B27>5)=0;
feature27(B27<=5)=-1;

feature27'
Was it helpful?

Solution

Based on this answer, how about this:

for i = 1:5

    A27_data = domain_URL{i};

    s = dir(strcat('f9data\','f7_data', int2str(i)));

    if s.bytes == 0
        B27(i) = NaN;
    else
        data2 = importdata(strcat('f9data\','f7_data', int2str(i)));
        feature27_data=(cellfun(@(n) ~isempty(n), strfind(data2, A27_data)));
        B27(i)=sum(feature27_data);

    end
end

Before loading any data, check if the file is empty or not. If it is, assign NaN to B27(i) (or any other default value). If the file actually contains data, run your processing on it.

Edit
If you don't like NaN, you can do something else, e.g.:

B27(i) = 0;

Edit 2

  • Stick with the B27(i) = NaN option.
  • After the if/else loop, insert this:

    if ~isnan(B27(i))
        B27(i) = data2
    end  
    
  • After the for-loop, insert this:

    B27(isnan(B27))=0;
    clear data2
    data2 = B27;
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top