Home Matlab: for loop and sprintf combination

# Matlab: for loop and sprintf combination

Yoni Verhaegen
1#
Yoni Verhaegen Published in 2018-02-13 14:06:02Z
 I have the following data: no_gridpoints = 640 % amount of columns in considered surfaceelevation % a 1x640 array with surface elevation Terskol1752, Terskol1753, ... Terskol2017 % 365x1 arrays with daily mean temperatures for 1 year of which the fifth colomn contains the temperature data  I want to create temp_glacier files with the corresponding year in the file name. This with a loop over all the years (1752-2017) by using the sprintf command in the loop: for k = 1752:2017 for m = 1:no_gridpoints sprintf('temp_glacier%d(m)',k) = sprintf('Terskol%d(:,5)',k) + surfaceelevation end end  However, I always get the error 'Subscripted assignment dimension mismatch.'. Can anyone tell me what I am doing wrong? Thanks
Wolfie
2#
 As stated in my comment: it looks like you're mistaking sprintf for eval. The expression within sprintf is not evaluated, so your assignment is stating "make this string = this other string added to an array" - it makes no sense. To correct your code as-is, you could do the following for k = 1752:2017 for m = 1:no_gridpoints eval(sprintf('temp_glacier%d(m) = Terskol%d(:,5) + surfaceelevation', k, k)) end end  This is a bad idea It would be far better practise for you to store your yearly data in a single cell array (or because it's numerical and the same size, just a standard matrix) rather than 266 individually named variables. I say better practise because if you to mean to use eval, you should know it should be avoided! This method would look like the following: Terskol = [ ... ] % your data here, in a 266*365 matrix where each row is a year for k = (1752:2017) - 1751 % We actually want to loop through rows 1 to 266 for m = 1:no_gridpoints % Your arrays were 1D, so you were originally getting a scalar temp val % We can do that here like so... temp_glacier(m) = Terskol(k, 5) + surfaceelevation; % Now do something with temp_glacier, or there was no point in this loop! % ... end end  Vectorising the inner loop: for k = (1752:2017) - 1751 % We actually want to loop through rows 1 to 266 temp_glacier = repmat( Terskol(k, 5) + surfaceelevation, 1, no_gridpoints ); % Do something with temp_glacier... end 
 You need to login account before you can post.
Processed in 0.307268 second(s) , Gzip On .