1

I've created an empty array with the name pattern and now I am reading a file that generates strings and each string I want to be saved in a variable p. I want the pattern to be displayed on the MATLAB command window. The line assigned to P should be stored in array pattern.

pattern=[]
while ~isnan(l)
        p=fgetl(fp);
pattern=(pattern,p[])
end

Can you help, I think I am doing it wrong to assign pattern. Because it wouldn't get the result

pattern = [];
while(~feof(fid))
    l = fgetl(fid);
    idx = regexp(l, '^information$');
    if size(idx,1)>0
        l = fgetl(fid); 
        while ~isnan(l)
            p = fgetl(fid);
        end 
    end
end

The above is the code

1
  • 2
    Please provide a functioning example so we can best answer your question. For variable length strings I would advise using a cell array. Also, concatenating arrays in every iteration of a loop is highly inefficient, consider preallocating the cell array for speed. Commented Aug 20, 2014 at 12:46

2 Answers 2

2

You need to use cells for this, thus the correct type of brackets is {}, not []. When the entire text is saved in a cell array, you can display it using a combination of cellfun and disp.

Something like this should work:

fid = fopen('textfile.txt');

p = fgetl(fid);
pattern = {p}
while ischar(p)
    p = fgetl(fid);
    pattern = [pattern; {p}];
end

fclose(fid);
cellfun(@disp, pattern)
Sign up to request clarification or add additional context in comments.

6 Comments

It says variable pattern appears to change size on every loop iteration. Consider p reallocating for speed
Minor comment (even though this solution is awesome). What about using celldisp for displaying cells?
@SamiyaQureshi - That is expected. The size of the cell array is changing at each iteration. What you are asking can't be done with pre-allocation.
@rayryeng, I don't think celldisp works well for this as the result will be: pattern{1} = (linebreak) function why(n) (linebreak) pattern{2} = (linebreak) etc. Thanks though =)
@RobertP. - Oh well I tried! You're welcome :) +1 btw.
|
1

if your strings have different length, then you should save them in a cell array.

%// create empty cell array
pattern=cell(0) 

while ~isnan(l)
    p=fgetl(fp);

    %// save in cell array
    pattern{end+1} = p

    %// show in command window
    disp(p) 
end

now you can access your first pattern with pattern{1} and your second with pattern{2}...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.