joining a character variable and a numerical variable to call a filename within a loop

조회 수: 3 (최근 30일)
how do i join the variable n to the variable filename to get the name of a real file that i want to call in a loop?
example
real files called: file 1, file 2 etc..
filename='file';
n=1:5;
for
some action filename + n;
end
many thanks
James

채택된 답변

Robert Cumming
Robert Cumming 2011년 2월 24일
there are lots of ways to do this, see num2str or using low level sprintf, a few examples:
fname = [ filename num2str(n) ];
fname = strcat ( filename, num2str(n) );
fname = sprintf ( '%s %i', filename, n );
I always use the last example
  댓글 수: 1
m naveed
m naveed 2016년 6월 20일
hi @Robert Cumming...i am using a nested for loop to place simulink blocks to form a 4 X 4 mesh of same element in combination with add_block and add_line function. how should i use num2str to name my elemens in the row differently than the elements in columns. e.g. for row elements, the blocks should bear the names B11 B12 B13 B14 and the next three rows should follow as...B21 B22 B23 B24 and so on until the 4x4th element to be B44

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Jan
Jan 2011년 2월 24일
See also the FAQ:
It is alway a good idea to look for an answer there before asking here.
  댓글 수: 2
james
james 2011년 2월 24일
I had a crack at searching for an answer, obviously I used the wrong search terms. When you don't have the right 'code' vocabulary it's not as easy as you think to find what you want.
I think I searched something like -joining variables? I Had a go with num2str but didn't quite use the right syntax.
I have banged my head on the desk in punishment :)
Jan
Jan 2011년 2월 24일
Take all the terms you have searched for and set them as tags to your question here, such that others will find it fast. You are not allone with this problem - otherwise it would not be in the FAQ...

댓글을 달려면 로그인하십시오.


james
james 2011년 2월 24일
Hi robert
thanks for your reply
i had been playing with num2str and sprintf but to no avail!
James
  댓글 수: 2
Robert Cumming
Robert Cumming 2011년 2월 24일
why not? What error are you getting?
Post some code.
james
james 2011년 2월 24일
all your answers work fine
it was my random combinations of num2str and sprintf that didn't work. sorry i should have been more clear

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by