Home Matlab: for loop and sprintf combination
Reply: 1

Matlab: for loop and sprintf combination

Yoni Verhaegen
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

However, I always get the error 'Subscripted assignment dimension mismatch.'. Can anyone tell me what I am doing wrong?


Wolfie Reply to 2018-02-13 16:14:59Z

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))

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!
        % ...

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...
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.307268 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO