- No need to use eval! It makes debugging difficult and more reason are available in the FAQ. And counting blips is error prone.
- Are you sure all meta data must be squeezed into the filename?
- Do you really want "random" dots in the filename?
creating strings with variables
91 次查看(过去 30 天)
显示 更早的评论
I have to access many different files with slightly different names and instead of manually writing them in matlab I want to dynamically create them. So I have:
mat_frac = zeros(21,21);
mat_Tp = zeros(21,21);
for i=1:21
for j=1:21
mat_frac(i,j)=i*0.0005;
mat_Tp(i,j)=1290+j*10;
end
end
mat_frac(end,:)=1.000;
mat_frac = mat_frac(:);
mat_Tp = mat_Tp(:);
for i=1:numel(mat_frac)
evalit = sprintf('file{%d}=nuPots_run1_120_1cm_%d_%1.3ffrac_h1_100km_0block_1salters_1mpyr_10dV;',i,mat_Tp(i),mat_frac(i));
eval(evalit);
end
But this does not work because I get the attempted operation:
file{1}=nuPots_run1_120_1cm_1300_0.001frac_h1_100km_0block_1salters_1mpyr_10dV;
instead of the correct:
file{1}='nuPots_run1_120_1cm_1300_0.001frac_h1_100km_0block_1salters_1mpyr_10dV';
But I cannot add the relevant apostrophe's in the sprintf line. So how do I correct this?
0 个评论
回答(2 个)
per isakson
2015-2-2
编辑:per isakson
2015-2-2
This code is much more complicated than needed.
for i=1:numel(mat_frac)
evalit = sprintf('file{%d}=nuPots_run1_120_1cm_%d_%1.3ffrac_h1_100km_0block_1salters_1mpyr_10dV;',i,mat_Tp(i),mat_frac(i));
eval(evalit);
end
Try something like
file{ii} = sprintf('nuPots_run1_120_1cm_%d_%1.3ffrac_..._10dV' ...
, mat_Tp(ii), mat_frac(ii) );
"But I cannot add the relevant apostrophe's in the sprintf line."   Do you want the filename to begin and end with an apostrophe? Isn't the value of file{ii} supposed to be a text string without enclosing blips?
0 个评论
Guillaume
2015-2-2
To add apostrophes to a string, you just double them:
s = 'some string with an apostrophe here -> '' <- and here -> '' <-';
As per isakson said, your whole code is very inefficient. I particularly don't understand why you went with eval. Get into the habit of never using eval. 99.9% of the time there's a more efficient way. Also, your first two loops are completely unnecessary:
[i, j] = ndgrid(1:21, 1:21);
mat_frac = i * 0.0005;
mat_Tp = 1290 + 10 * j;
mat_frac(end, :) = 1;
You also don't need to reshape (with (:)) your matrices if you're using linear indexing:
files = cell(1, numel(mat_frac);
for fidx = 1:numel(mat_frac)
files{fidx} = sprintf('nuPots_run1_120_1cm_%d_%1.3ffrac_h1_100km_0block_1salters_1mpyr_10dV', mat_Tp(fidx), mat_frac(fidx));
end
Or you could use arrayfun to replace the loop:
files = arrayfun(@(t,f) sprintf('nuPots_run1_120_1cm_%d_%1.3ffrac_h1_100km_0block_1salters_1mpyr_10dV', t, f), mat_Tp(:), mat_frac(:), 'UniformOutput', false); %and no need to predeclare files.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Import and Analysis 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!