I have a .m file that contains a struct with some matrices:
%mymatfile.m
function [mymatrix,anothermatrix] = mymatfile;
mymatrix = [
1 2 0.0010 0.0010 0.0000 2.0000 2.0000 2.0000 1 0 1
2 3 2.0014 0.0007 0.0000 0.5000 0.5000 0.5000 0 0 1
3 4 0.0301 0.0001 4.0000 0.5000 0.5000 0.5000 1.16 0 1
4 5 0.0791 0.0450 0.0000 0.5000 0.5000 0.5000 0 0 1
5 6 1.0482 0.0233 0.0000 0.5000 0.5000 0.5000 0 0 1
5 7 7.5130 0.0467 0.0000 0.5000 0.5000 0.5000 0* 0 1
7 8 9.0161 0.0008 0.0000 0.5000 0.5000 0.5000 0 0 1
7 9 0.9070 0.2310 0.0000 0.5000 0.5000 0.5000 0 0 1
];
anothermatrix = [
2 0 0 3 0 10 0
9 0 0 3 0 10 0
%];
How do I change just the starred value (mymatrix(3,9)) and save the file, whilst retaining its structure/formatting? I need to perform the update from another matlab script.
You could save the entries of mymatrix
in a text file, say mymatrix_text
.
Then you make your function read that text file, ie
%mymatfile.m
[mymatrix,anothermatrix] = function get_my_matrices()
fid = fopen(mymatrix_text);
mymatrix = fscanf(fid, '%g ');
fclose(fid);
% anothermatrix = %% you can do the same above..
end
Now if you need to modify your matrix, you should just modify the text file -which is way easier and doesn't involve changing your .m
file.
(For instance you may create another function to read mymatrix_text
and change the desired values).
This approach looks more robust to me.
Substitute a number in for the old one. The fields seem to be tab delimited.
Here's how I did it in the end (note that S
is the value used to update the file):
fid = fopen('mymatfile.m') % open settings file
fseek(fid,1196,-1) % set read position
Line = fgets(fid) % read in line
Refline = Line % set reference for search and replace later
Line(47:51) = S % update specific characters in the line with new setting
fclose(fid) % close file
wholefile = fileread('test.m') % read in entire file
newfiledata = strrep(wholefile,Refline,Line) % replace line
fid2 = fopen('mymatfile.m','w') % open file to write
fprintf(fid2,'%s',newfiledata) % save to file
fclose(fid2)
With help from here: [http://www.mathworks.com/matlabcentral/answers/7066].
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.