Open In App

MATLAB – Read Words in a File in Reverse Order

MATLAB stands for Matrix Laboratory. It is a high-performance language that is used for technical computing. It allows matrix manipulations, plotting of functions, implementation of algorithms, and creation of user interfaces

Suppose we are given a text file containing the following words “I STUDY FROM GEEKS FOR GEEKS”. Now, if we want to read the words of the file in the reverse order, the outcome should be “GEEKS FOR GEEKS FROM STUDY I”.



Algorithm:

Example 1: 




% MATLAB program for read words
% Opening the given file to read,
% name of the file is passed as
% an argument in fopen() function.
fp=fopen('rev.txt');
 
% Using fseek(),
% we will move fp to the end of file.
fseek(fp,0,'eof');
 
% Finding the position of fp using ftell()
fsz=ftell(fp);
i=1;
 
% Using fseek(), move fp to
% the current-1 position.
fseek(fp,-1,'cof');
 
% Using fread(),read a character
chr=fread(fp,1,'*char');
 
% Store the character in the matrix Z.
Z(1,i)=chr;
Word=0;
 
% Checking if fp has reached to
% start of the file.
    while(fseek(fp,-2,'cof')~=-1)
        
        c=fread(fp,1,'*char');
        % Character array is
        % reversed and appended into a string when a space occurs.
        if(isspace(chr))
              if(Word==0)
                  %Step 9- At first, the string is empty.
                  % Step 10- Now, the array is appended in
                  % the reverse order with a blank space.
                   Word=[fliplr(Z) blanks(1)];
              else
                  % Append the reversed character
                  % array to the string
                   Word=[Words fliplr(Z)];
              end
           i=1;
           Z='';
        else
            % The array is updated with the
            % characters until blank space is
            % encountered
           i=i+1;
           Z(1,i)=chr;
           
        end
 
 
    end
    
Word=[Word fliplr(Z)];
display(Word);
 
fclose(fp);

Output:



 


Article Tags :