0

I want to iteratively define a variable whose name is the concatenation of two strings.

In particular, the following code is meant to create a variable Uvel_spring that contains the values Uvel stored in the file spring_surface.mat :

seasons{1}='spring';
seasons{2}='summer';
seasons{3}='autumn';
seasons{4}='winter';

for ii=1:4

    ['Uvel_',char(seasons(ii))] = load([char(seasons(ii)),'_surface.mat'],...
             'Uvel');

end

However, I get the following error:

An array for multiple LHS assignment cannot contain LEX_TS_STRING.

I solved it by using evalc:

for ii=1:4

   evalc( sprintf(['Uvel_',char(seasons(ii)),'=','load(''',char(seasons(ii)),'_surface.mat'',',...
             '''Uvel''',')']) );

end

However, it is horrible and I would like to improve the code.

Does someone have an alternative solution?

1 Answer 1

2

Use struct instead.

for ii=1:4
    Uvel.(seasons{ii}) = load([seasons{ii},'_surface.mat'], 'Uvel');
end

You'll end up having those four seasons as the fields of Uvel. So you'll be accessing Uvel_spring as Uvel.spring and similarly for others.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.