Strings and numbers, strcat and num2str

조회 수: 1 (최근 30일)
Syed Ali Mohsin Bukhari
Syed Ali Mohsin Bukhari 2017년 2월 6일
댓글: Syed Ali Mohsin Bukhari 2017년 2월 6일
I'm working with SDSS data and want to get rid of some fits files from the ones I have downloaded. I have stored the pl #, mjd, fb # in respective variables and the format of SDSS file naming is spec-plate-mjd-fiber.fits where
  • plate ranges from 250-3500
  • mjd is always 5 digits
  • fiber is 1-640.
I want to concatenate the plate, mjd and fiber number to check for the files and exclude/move them. Here's my code
Tz = '-000'; tz = '-00'; oz = '-0'; j=1;
for j=1:length(pl)
if and(pl(j) < 999, fb(j) < 10)
b = ['spec-0', num2str(pl(j)), '-', num2str(mj(j)), Tz, num2str(fb(j))];
end
if and(pl(j) < 999, or(fb(j) >= 10, fb(j) < 100))
b = ['spec-0', num2str(pl(j)), '-', num2str(mj(j)), tz, num2str(fb(j))];
end
if and(pl(j) < 999, or(fb(j) >= 100, fb(j) < max(fb)))
b = ['spec-0', num2str(pl(j)), '-', num2str(mj(j)), oz, num2str(fb(j))];
end
if and(pl(j) >= 1000, fb(j) < 10)
b = ['spec-', num2str(pl(j)), '-', num2str(mj(j)), Tz, num2str(fb(j))];
end
if and(pl(j) >= 1000, or(fb(j) >= 10, fb(j) < 100))
b = ['spec-', num2str(pl(j)), '-', num2str(mj(j)), tz, num2str(fb(j))];
end
if and(pl(j) >= 1000, or(fb(j) >= 100, fb(j) < max(fb)))
b = ['spec-', num2str(pl(j)), '-', num2str(mj(j)), oz, num2str(fb(j))];
end
c{j} = b;
end
The problem is with fb < 100, it gives spec-1835-54563-077 instead of spec-1835-54563-0077 and same with fb < 10. How can I solve this?
  댓글 수: 2
Stephen23
Stephen23 2017년 2월 6일
편집: Stephen23 2017년 2월 6일
Note that the concatenations and multiple num2str should be replaced with one sprintf:
b = ['spec-0', num2str(pl(j)), '-', num2str(mj(j)), oz, num2str(fb(j))];
% vs.
b = sprintf('spec-0%f-%f%s%f',pl(j),mj(j),oz,fb(j));
Syed Ali Mohsin Bukhari
Syed Ali Mohsin Bukhari 2017년 2월 6일
oz wasn't needed that much. I just initialized it because I was too lazy to write -0 again and again, same with Tz and tz, but yes by using sprintf my problem got solved. Thank you .

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

채택된 답변

James Tursa
James Tursa 2017년 2월 6일
편집: James Tursa 2017년 2월 6일
Is this what you want?
b = sprintf('spec-%04d-%05d-%04d',pl(j),mj(j),fb(j));
  댓글 수: 1
Syed Ali Mohsin Bukhari
Syed Ali Mohsin Bukhari 2017년 2월 6일
편집: Syed Ali Mohsin Bukhari 2017년 2월 6일
You shrank the code, a little too much. Thank you, this did the trick.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by