Search code examples
matlabmatrixexportfile-conversion

Taking symbolic variables out of txt file and making a matrix in Matlab


I have a txt file containing following characters. theta1 , l1 and others are symbolic variables.( Don't mind about it)

 M=[theta1 + (l1^2*m1)/4 + l1^2*m2 (l1*l2*m2*cos(fi1 - fi2))/2 ; 
 (l1*l2*m2*cos(fi1 - fi2))/2 theta2 + (l2^2*m2)/4 ]

I need to take it out and make it a symbolic matrix. As you can see txt file is already fine for making matrix but I don't want to copy paste the whole thing to script, I rather want to do it automatically.

fid = fopen('a.txt');
MMatrix=textscan(fid,'%s');
fclose(fid);

I tried the code above but it turn out to be not useful. What do you think is the way to copy the whole thing and use it for matrix making?


Solution

  • Instead of reading that as a string or a character array and then possibly resorting to evil (eval) method, just rename the extension from txt to m since you already have your arrays defined in the MATLAB way in the text files. Maintain a backup copy of those original txt files if needed.

    If it is a single file (a.txt), you can rename it manually or with this code to a.m:

    movefile('a.txt', 'a.m');
    

    If there are multiple such files in a directory then you can use the following code to change the extension of all such txt files in the current directory:

    txtfiles = dir('*.txt');   %getting all txt files in the current directory
    for num = 1:numel(txtfiles)
        [~, fname] = fileparts(txtfiles(num).name);  %filename (without extension)
        movefile(txtfiles(num).name, [fname,'.m']);  %renaming
    end
    

    Now you can simply use the name of the respective file in your script to get whatever arrays that file have in it.