How to associate .slx file with Simulink - simulink

I would like to be able to double-click a .slx file and have it open up in Simulink. If MATLAB is already open, I would prefer that it not open a second instance of MATLAB.
Challenges include:
unable to find .exe to associate .slx file with
Google search did not reveal solution to this challenge
Actionable suggestions or examples are appreciated
Associating .slx with matlab.exe looks like this:
My peers with OSX show .slx associated with this icon:
Starting the Simulink Software

Had the same problem. Here is the solution, it worked fine for my R2018b.
Run this file in Matlab and it will produce .reg file that will fix the problem (run it of course). Than restart yor PC.
Here is the code of the file if you can't (or don't want to) sign in to download it:
function associateFiles(action, userExtList, fileStr)
% Defualt input
if (nargin < 1 || isempty(action))
action = 'add';
end
if (nargin < 2)
userExtList = {};
end
if (nargin < 3)
fileStr = '';
end
if (~iscell(userExtList))
if (isempty(userExtList))
userExtList = {};
else
userExtList = {userExtList};
end
end
% Sanity check
if (~ischar(action) || (~strcmpi(action, 'add') && ...
~strcmpi(action, 'delete') && ~strcmpi(action, 'deleteadd')))
error('The action to perform must be ''add'', ''delete'' or ''deleteadd''!')
end
if (~isempty(userExtList) && ~min(cellfun(#ischar, userExtList)))
error('The file extension list must be a string or a cell array of strings!')
end
if (~ischar(fileStr))
error('The file to write to must be a string!')
end
% Get the currently running MATLAB version
verStr = regexp(version, '(\d*?\.\d*?\.\d*?)\.', 'tokens');
verStr = verStr{1}{1};
verNum = str2double(regexprep(verStr, '(\d*?\.\d*)[\x0000-\xffff]*', '$1'));
verHex = sprintf('%04x', str2double(regexprep(verStr, ...
'(\d*?)\.[\x0000-\xffff]*', '$1')), str2double(regexprep(verStr, ...
'\d*?\.(\d*?)\.[\x0000-\xffff]*', '$1')));
% Get 32/64-bit
arch = computer;
switch arch
case 'PCWIN'
binFolder = 'win32';
case 'PCWIN64'
binFolder = 'win64';
end
binPath = fullfile(matlabroot, 'bin', binFolder);
% Known MATLAB files with possible DDE actions
fileExtCell = {...
'fig' , 'MATLAB Figure' , '-62' , ...
{'Open', 'uiopen(''%1'',1)'} , [] ; ...
'm' , 'MATLAB Code' , '-58' , ...
{'Open', 'uiopen(''%1'',1)'} , {'Run', 'run(''%1'')'} ; ...
'mat' , 'MATLAB Data' , '-59' , ...
{'Load', 'load(''%1'')' } , {'Open', 'uiimport(''%1'')'}; ...
'mdl' , 'Simulink Model' , '-61' , ...
{'Load', 'uiopen(''%1'',1)'} , [] ; ...
'mdlp' , 'Simulink Protected Model' , '-72' , ...
[] , [] ; ...
'mexw32', 'MATLAB MEX' , '-63' , ...
[] , [] ; ...
'mexw64', 'MATLAB MEX' , '-63' , ...
[] , [] ; ...
'mn' , 'MuPAD Notebook' , '-66' , ...
{'Open', 'mupad(''%1'')'} , [] ; ...
'mu' , 'MuPAD Code' , '-67' , ...
{'Open', 'uiopen(''%1'',1)'} , [] ; ...
'muphlp', 'MuPAD Help' , '-68' , ...
{'Open', 'doc(symengine, ''%1'')'} , [] ; ...
'p' , 'MATLAB P-code' , '-60' , ...
[] , [] ; ...
'slx' , 'Simulink Model (SLX format)', '-73' , ...
{'Open', 'uiopen(''%1'',1)'} , [] ; ...
'ssc' , 'Simscape Model' , '-65' , ...
{'Open', 'uiopen(''%1'',1)'} , [] ; ...
'xvc' , 'MuPAD Graphics' , '-69' , ...
{'Open', 'mupad(''%1'')'} , [] ; ...
'xvz' , 'MuPAD Graphics' , '-70' , ...
{'Open', 'mupad(''%1'')'} , [] ; ...
'mlapp' , 'MATLAB Application' , [] , [], [] ; ...
'mltbx' , 'MATLAB Toolbox' , [] , [], [] ; ...
'mldatx' , 'Simulink Scenario' , [] , [], [] ; ...
'req' , 'Simulink Requirements Link' , [] , [], [] ; ...
'sldd' , 'Simulink Dictionary' , [] , [], [] ; ...
'slddc' , 'Simulink Dictionary' , [] , [], [] ; ...
'mlappinstall', 'MATLAB Application' , [] , [], [] ; ...
'mlpkginstall', 'MATLAB Support Package' , [] , [], [] ; ...
'slxp' , 'Simulink Protected Model Package', [] , [], [] ; ...
'sltx' , 'Simulink Template' , [] , [], [] ; ...
'mlprj' , 'MATLAB Project' , [] , [], []};
% Possibly trim list
if (~isempty(userExtList))
fileExtCell = fileExtCell(ismember(fileExtCell(:, 1), ...
regexprep(userExtList, '\.', '')), :);
end
% Make registry file
if (~isempty(fileStr))
% Possibly add file extension
[~, ~, tmp] = fileparts(fileStr);
if (isempty(tmp))
fileStr = [fileStr, '.reg'];
end
fid = fopen(fileStr, 'w');
else
fid = fopen('MatlabFileAssocFix.reg', 'w');
end
if (fid == -1)
error('Failed to create registry file')
end
% Write intial lines
fprintf(fid, '%s\r\n\r\n', 'Windows Registry Editor Version 5.00');
fprintf(fid, '%s\r\n\r\n', ';FIXES MATLAB FILE ASSOCIATIONS');
% REMOVE OLD KEYS
explorerKey = ['HKEY_CURRENT_USER\Software\Microsoft\Windows\', ...
'CurrentVersion\Explorer\FileExts'];
% Iterate over file extensions
for fileExtNo = 1 : size(fileExtCell, 1)
rmKeys = {};
fileExt = fileExtCell{fileExtNo, 1};
% File extension keys
[status, result] = dos(['reg query HKEY_CLASSES_ROOT /f .', fileExt, ...
' /k /e']);
if (~status)
keys = regexp(result, '(HKEY_CLASSES_ROOT[\x0000-\xffff]*?)\n', 'tokens');
rmKeys = [rmKeys, keys{:}];
end
% Old style keys without version numbers
if (~strcmpi(fileExt, 'mexw64'))
% Uses single DDE key for mex files
if (strcmpi(fileExt, 'mexw32'))
fileExtTmp = 'mex';
else
fileExtTmp = fileExt;
end
[status, result] = dos(['reg query HKEY_CLASSES_ROOT /f ', ...
fileExtTmp, 'file /k /e']);
if (~status)
keys = regexp(result, '(HKEY_CLASSES_ROOT[\x0000-\xffff]*?)\n', ...
'tokens');
rmKeys = [rmKeys, keys{:}];
end
end
% New style keys with version number
if (strcmpi(action, 'add'))
% Only remove keys related to this version
[status, result] = dos(['reg query HKEY_CLASSES_ROOT /f MATLAB.', ...
fileExt, '.', verStr ' /k']);
else
% Remove keys related to ALL version
[status, result] = dos(['reg query HKEY_CLASSES_ROOT /f MATLAB.', ...
fileExt, '. /k']);
end
if (~status)
keys = regexp(result, '(HKEY_CLASSES_ROOT[\x0000-\xffff]*?)\n', 'tokens');
rmKeys = [rmKeys, keys{:}];
end
% Explorer keys
[status, result] = dos(['reg query ', explorerKey, ' /f .', fileExt, ...
' /k /e']);
if (~status)
keys = regexp(result, '(HKEY_CURRENT_USER[\x0000-\xffff]*?)\n', 'tokens');
rmKeys = [rmKeys, keys{:}];
end
% Write to file
if (~isempty(rmKeys))
fprintf(fid, '%s\r\n\r\n', [';REMOVES ', upper(fileExt), ...
' FILE ASSOCIATIONS']);
for keyNo = 1 : length(rmKeys)
key = rmKeys{keyNo};
fprintf(fid, '%s\r\n\r\n', ['[-', key, ']']);
end
end
end
% ADD KEYS
if (~strcmpi(action, 'delete'))
% Get text Persistent Handler
[status, result] = dos(...
'reg query HKEY_CLASSES_ROOT\.txt\PersistentHandler /ve');
if (~status)
PersistentHandler = regexp(result, '\{[\x0000-\xffff]*?\}', 'match');
PersistentHandler = PersistentHandler{1};
else
PersistentHandler = '';
end
% DDE call
ddeCall = 'ShellVerbs.Matlab';
if (verNum > 8)
% Changed from R2013a
ddeCall = [ddeCall, '.', verStr];
end
% Default icon
defIcon = 'm';
if (~exist(fullfile(binPath, 'm.ico'), 'file'))
defIcon = '';
end
% Path to MATLAB binary directory with \\
binPathStr = regexprep(binPath, '\\', '\\\\');
% Write Shell Open key
key = ['[HKEY_CLASSES_ROOT\Applications\MATLAB.exe\shell\open', ...
'\command]%r', '#="\"', binPathStr, '\\MATLAB.exe\" \"%1\""%r%r'];
fprintf(fid, '%s\r\n\r\n', ';ADD SHELL OPEN');
lines = regexp(key, '([\x0000-\xffff]*?)%r', 'tokens');
for lineNo = 1 : length(lines)
fprintf(fid, '%s\r\n', lines{lineNo}{1});
end
% Iterate over file types
for fileExtNo = 1 : size(fileExtCell, 1)
fileExt = fileExtCell{fileExtNo, 1};
% File extension keys
key = ['[HKEY_CLASSES_ROOT\.', fileExt, ']%r#="MATLAB.', fileExt, '.', ...
verStr, '"%r'];
if (strcmpi(fileExt, 'm') && ~isempty(PersistentHandler))
% Add some values
key = [key, '"Content Type"="text/plain"%r', ...
'"PerceivedType"="Text"%r'];
end
key = [key, '%r'];
key = [key, '[HKEY_CLASSES_ROOT\.', fileExt, ...
'\OpenWithProgids]%r"MATLAB.', fileExt, '.', verStr, '"=""%r%r'];
if (strcmpi(fileExt, 'm') && ~isempty(PersistentHandler))
key = [key, '[HKEY_CLASSES_ROOT\.', fileExt, ...
'\PersistentHandler]%r#="', PersistentHandler, '"%r%r'];
end
key = [key, '[HKEY_CLASSES_ROOT\.', fileExt, ...
'\Versions\MATLAB.', fileExt, '.' verStr, ']%r"FileVersionMS"=dword:', ...
verHex, '%r"FileVersionLS"=dword:00000000%r%r'];
% DDE keys
ddeData = fileExtCell(ismember(fileExtCell(:, 1), fileExt), :);
key = [key, '[HKEY_CLASSES_ROOT\MATLAB.', fileExt, '.' verStr, ...
']%r#="', ddeData{2}, '"%r'];
if (~isempty(ddeData{3}))
key = [key, '"FriendlyTypeName"="#', binPathStr, '\\matlab.exe', ...
',', ddeData{3}, '"%r'];
end
key = [key, '%r'];
% Icon
icon = fileExt;
if (~exist(fullfile(binPath, [icon, '.ico']), 'file'))
icon = defIcon;
end
if (~isempty(icon))
key = [key, '[HKEY_CLASSES_ROOT\MATLAB.', fileExt, '.' verStr, ...
'\DefaultIcon]%r#="', binPathStr, '\\', icon, '.ico,0"%r%r'];
end
% Shell actions
for shellActionNo = 4:5
ddePar = ddeData{shellActionNo};
if (~isempty(ddePar))
key = [key, '[HKEY_CLASSES_ROOT\MATLAB.', fileExt, '.' verStr, ...
'\Shell\', ddePar{1}, ']%r#="', ddePar{1}, '"%r%r'];
key = [key, '[HKEY_CLASSES_ROOT\MATLAB.', fileExt, '.' verStr, ...
'\Shell\', ddePar{1}, '\command]%r#="\"', binPathStr, ...
'\\matlab.exe\""%r%r'];
key = [key, '[HKEY_CLASSES_ROOT\MATLAB.', fileExt, '.' verStr, ...
'\Shell\', ddePar{1}, '\ddeexec]%r#="', ddePar{2}, '"%r%r'];
key = [key, '[HKEY_CLASSES_ROOT\MATLAB.', fileExt, '.' verStr, ...
'\Shell\', ddePar{1},'\ddeexec\application]%r#="', ...
ddeCall, '"%r%r'];
key = [key, '[HKEY_CLASSES_ROOT\MATLAB.', fileExt, '.' verStr, ...
'\Shell\', ddePar{1},'\ddeexec\topic]%r#="system"%r%r'];
end
end
% Explorer keys
key = [key, '[', explorerKey, '\.', fileExt, '\OpenWithProgids]%r'];
if (strcmpi(fileExt, 'm'))
key = [key, '"m_auto_file"=hex(0):%r'];
end
key = [key, '"MATLAB.', fileExt, '.', verStr, '"=hex(0):%r%r'];
if (~isempty(ddeData{4}))
% Add key
key = [key, '[', explorerKey, '\.', fileExt, ...
'\OpenWithList]%r"a"="MATLAB.exe"%r"MRUList"="a"%r%r'];
else
key = [key, '[', explorerKey, '\.', fileExt, '\OpenWithList]%r%r'];
end
% Write to file
fprintf(fid, '%s\r\n\r\n', [';ADD ', upper(fileExt), ...
' FILE ASSOCIATIONS']);
lines = regexp(key, '([\x0000-\xffff]*?)%r', 'tokens');
for lineNo = 1 : length(lines)
fprintf(fid, '%s\r\n', lines{lineNo}{1});
end
end
end
% Cloese file
fclose(fid);

Related

Transform matrix to one-line representation for copy&paste

Suppose I have an output which is a large array, say 500x4.
I would like to transform this array into code form to create the same array.
An example:
output_array = randn(2,3)
output_array =
-0.2408 -0.9390 1.1794
-0.9064 0.1178 -0.4643
I would like to obtain:
input_array = [-0.2408 -0.9390 1.1794; -0.9064 0.1178 -0.4643]
For low dimensions, manual work is easy, but I would to be able to obtain the input code for arbitrary matrices.
Thanks.
This is one way:
a = randi(2,3)
linespec = [repmat('%d ',1,size(a,2)) '; ']
spec = strrep(['[ ' repmat(linespec,1,size(a,1)) ' ]'],'; ','')
b = sprintf(spec,a(:) )
a =
2 2 1
1 1 1
1 2 2
linespec =
%d %d %d ;
spec =
[ %d %d %d ; %d %d %d ; %d %d %d ]
b =
[ 2 1 1 ; 2 1 2 ; 1 1 2 ]
Be aware, that the number of spaces defined in ' ... ' snippets do matter!
use:
spec = ['b = ' strrep(['[ ' repmat(linespec,1,size(a,1)) ' ]'],'; ','') ]
to get:
b =
b = [ 1 2 2 ; 1 2 2 ; 1 2 1 ]
It could be interesting to wrap everything into a function:
function [ out ] = Matrix2String( a )
varname = inputname(1);
linespec = [repmat('%d ',1,size(a,2)) '; '];
spec = [varname ' = ' strrep(['[ ' repmat(linespec,1,size(a,1)) ' ]'],'; ','') ];
out = sprintf(spec,a(:) );
end
a call like:
a = randi(2,3)
Matrix2String(a)
would then return:
ans =
a = [ 2 1 1 ; 2 1 2 ; 1 1 1 ]

Getting error from: dlen = uint32(0) ;

I don't know why but I am getting this error:
Error in mr_lsbpex (line 3)
dlen = uint32(0) ;
Output argument "a" (and maybe others) not assigned during call to "E:\path\mr_lsbpex.m>mr_lsbpex"
I have tested "dlen = uint32(0) ;" in matlab enviorment (outside of this function) and everything was OK. Here is my code:
function a = mr_lsbpex ( r, p )
% extract from an array
dlen = uint32(0) ;
s = size (r) ;
rnd = rand (s(1),s(2)) ;
rd = 32 ;
rl = s(2) ;
for i=1:s(2)
if rnd(1,i)<rd/rl
d = bitget (round(r(1,i)/p),1);
dlen = bitset (dlen,rd,d);
rd = rd -1 ;
end
rl = rl -1 ;
end
if (dlen > 10000000 )
clear a ;
return ;
end
a = uint8(zeros(dlen,1)) ;
rd = double(dlen * 8) ;
rl = double(s(1)*s(2)-s(2)) ;
for i=2:s(1)
for j=1:s(2)
if rnd(i,j)<rd/rl
d = bitget (round(r(i,j)/p) ,1) ;
a = z_set_bit (a,rd,d) ;
rd = rd - 1 ;
end
rl = rl - 1 ;
end
end
Remember: a needs to be returned ALLWAYS!
The error is not in that specific line, but in the "whole" function itself.
Your problem is that Matlab thinks that a its not going to be created. And actually in some case it may not be created.
The following line in the beginning of your function should do the trick
a=0; % well, or a=NaN; or whatever you want to return
Additionally, don't clear a in if (dlen > 10000000 ).

Ini file read and write + add new property + matlab [duplicate]

This question already has an answer here:
Property_value + matlab
(1 answer)
Closed 9 years ago.
How to read and write ini files: I want to add new property to an existing one. I want to write the ini file to temp file and finally add the new property to it. the new property will have head,name,desc, value and layout (like: line 1 & 3)
#---------------
# head
# --------------
[name]% type
# desc
value
fileData = [];
fh = fopen( fileName, 'r' ); % read handle
tname=tempname();
wfh =fopen(tname,'w'); % write handle
line = fgetl(fh);
val = '';
Prop ='';
type = '';
header = '';
desc= '';
while ischar(line)
if strcmpi(line(1),'#') && strcmpi(line(3),'=')
layout = line(2:end);
elseif strcmpi(line(1),'#')&& ~strcmpi(line(3),'=')
header = line(2:end);
else
Prop = regexp(line,{'\[*\w+\]\s*%\s*.*\s*'},'match');
[property data_type] = strtok(Prop,'%')
prop_p = property{1};% property_name
prop_per = regexprep(prop_p,{'\[','\]'},'');
prop = prop_per{1};
Dtype = data_type{1}; % datatype
dtype = strtrim(strrep(Dtype,'%',''));
DATA_type = dtype{1};
end
% How can i define filedname (prop) for the 'layout' and 'header' as they are found in lines before the actual'prop'.
% From command window
% Undefined variable prop.
% Error in ecco2511>add (line 212)
% fileData.(prop{1}).layout = layout;
desc = fgetl(fh); % description
desc = desc(1:end);
line = fgetl(fh);
val = line(1:end);
fileData.(prop).layout = layout;
fileData.(prop).header = header;
fileData.(prop).type = DATA_type;
fileData.(prop).desc = desc;
fileData.(prop).val = val;
line = fgetl(fh); % keep reading
end
if ~isfield( fileData, propName)
fileData.(propName).val = newVal;
fileData.(propName).type = datatype;
fileData.(propName).desc = description;
fileData.(propName).layout = layout;
fileData.(propName).header = header;
else
error ( 'property %s already exists, use set to change its value',propName );
end
fileData = orderfields( fileData );
propNames = fieldnames( fileData );
for ii = 1:numel( propNames )
fprintf(wfh,'%s\r',fileData.(propNames{ii}).layout);
fprintf(wfh,'\n');
fprintf(wfh,'%s\r',fileData.(propNames{ii}).header);
fprintf(wfh,'\n');
fprintf(wfh,'%s\r',fileData.(propNames{ii}).layout);
fprintf(wfh,'\n');
fprintf( wfh, '[%s]%s\r', (propNames{ii}),fileData.(propNames{ii}).type);
fprintf(wfh,'\n');
fprintf( wfh,'#%s\r',fileData.(propNames{ii}).desc);
fprintf(wfh,'\n');
fprintf( wfh,'%s\r',fileData.(propNames{ii}).val);
fprintf(wfh,'\n');
end
fclose(fh);
fclose(wfh);
[status,errmsg]= movefile(tname,fileName,'f');
Sounds like you need INI Config from MATLAB File Exchange. It will allow you to read, write, and modify INI style files. I have used it a number of times and it works quite well.

How to sort property -value pair in alphabetical order with Matlab

I want to add a property-value pair to existing file. In the mean time all the properties should be ordered in alphabetical order. For example :
[Info] % property 1
value 1
[system] % property 2
value 2
How can i add additional property such that all properties will be sorted in alphabetical order. I was able to add property -value pair to the end of the file using
fh = fopen(filename,'a') but i am not able to sort them alphabetically.
so far i tried this as follows but with this one it keeps printing only the new property-value pair . I want to print remaining properties onces it prints the new one.
function [] = myfun(filename ,propName,propvalue)
rfh = fopen(filename,'r');
tname = tempname();
wfh = fopen(tname,'w');
line = fgetl(rfh);
while ischar(line)
if (line(1) == '[') && (line(end) == ']')
property = lower(line(2:end-1)) % from ini file
String2 = property;
String1 = propName;
[sat] = sor(String1,String2)% subfunction
if sat == -1
fprintf(wfh,'[%s]\r\n%s\r\n',propName,propvalue);
else
fprintf(wfh,'%s\r\n',line);
end
else
fprintf(wfh,'%s\r\n',line);
end
line = fgetl(rfh);
end
fclose(rfh);
fclose(wfh);
movefile(tname,filename,'f')
function [sat] = sor(String1,String2)
Index = 1;
while Index < length(String1) && Index < length(String2) && String1(Index) == String2(Index)
Index = Index + 1;
end
% Return the appropriate code
if String1(Index) < String2(Index)
sat= -1
elseif String1(Index) > String2(Index)
sat= +1
else % the characters at this position are equal -- the shorter of the two strings should be "less than"
if length(String1) == length(String2)
sat = 0
elseif length(String1) < length(String2)
sat = -1
else
sat = +1
end
end
Is this a .ini file? You might want to take a look at INIConfig from the MATLAB File Exchange, a set of routines for handling INI files arranged in a convenient class. I haven't used it, but perhaps it might do what you need.
If not, you can always:
Read in the file
Loop through it line by line
When you find a line starting with [ followed by a word alphabetically later than the property you'd like to insert, insert your property and value
Include the remainder of the file
Write the whole file back out again.
How about read the file into a struct?
function fileData = readFileIntoStruct( fileName )
%
% read [property] value pairs file into struct
%
fh = fopen( fileName, 'r' ); % read handle
line = fgetl( fh );
while ischar( line )
% property
tkn = regexp( line, '\[([^\]+)]\]', 'once', 'tokens' );
% read next line for value
val = fgetl( fh );
fileDate.(tkn{1}) = val;
line = fgetl( fh ); % keep reading
end
fclose( fh ); % don't forget to close the file at the end.
Now you have all the data as a struct with properties as fieldnames and values as the field value.
Now you can update a property simply by:
function fileData = updateProperty( fileData, propName, newVal )
if isfield( fileData, propName )
fileData.(propName) = newVal;
else
warning( 'property %s does not exist - please add it first', propName );
end
You can add a property:
function fileData = addProperty( fileData, propName, newVal )
if ~isfield( fileData, propName )
fileData.(propName) = newVal;
else
warning ( 'property %s already exists, use update to change its value', propName );
end
You can sort the properties alphabetically using orderfields:
fileData = orderfields( fileData );
You can write the struct back to file simply using:
function writeDataToFile( newFileName, fileData )
fopen( newFileName , 'w' ); %write handle
propNames = fieldnames( fileData );
for ii = 1:numel( propNames )
fprintf( fh, '[%s]\r\n%s\r\n', propNames{ii}, fileData.(propNames{ii}) );
end
fclose( fh );
Assumptions:
The properties' names are legitimate Matlab field names (see variable naming for details).
The value of each property is always a string.
I did not include any error-checking code in these examples (files not found, wrongly formatted strings, etc.)
I assume the input file is strictly "[prop] val" pairs without any additional comments etc.

How to update txt file in matlab

I want to update a line in a txt file which contains property-values pairs, where a property is between square brackets and its value in the line below. This is an example file: On top of that i want to ignore the comment lines started with '#'. On the other hand what if i want to add comments to the comment line?
#===========================
#===========================
[system]
# comment
programming
#===========================
[information]
#
application
In this example, ´system´ is a property and ´programming´ its value. The same way, ´information´ is another property and ´application´ its value.
I want to call my function with a property-value pair and update the corresponding values in the txt file. Until now I have the following:
fh = fopen(filename,'r');
fh= fopen(filename,'w');
while ~feof
line = fgetl(fh);
if(line(1) == '[') && (line(end) == ']')
value = lower(line(2:end-1));
Then I will compare the 'value' with my input to check if it matches with property. If so I should update the next line with the new input. Finally I have to write to the original file.
For this sample txt how can I update the word 'programming' to 'system information'?
How about
function [] = updateFile( fileName, propName, newProbVal )
%
% update file fileName, replacing the value of propName with newPropVal
%
% all inputs are strings
%
rfh = fopen( fileName, 'r' ); % read handle
tname = tempname(); % temporary file name
wfh = fopen( tname, 'w' );
% read line by line
foundFlag = false;
line = fgetl( rfh );
while ischar(line)
if foundFlag
fprintf( wfh, '%s\r\n', newProbVal );
foundFlag = false;
else
fprintf( wfh, '%s\r\n', line );
end
tks = regexp( line, ['^\[',propName,'\]'] );
foundFlag = ~isempty(tks);
line = fgetl( rfh );
end
fclose( rfh );
fclose( wfh );
movefile( tname, fileName, 'f' ); % rename temp file name