Repeated string what been increment by 1?

조회 수: 4 (최근 30일)
Hesham Ismail
Hesham Ismail 2015년 7월 28일
댓글: Hesham Ismail 2015년 7월 28일
Hello,
I have this code below that have a lot of repeated parts which are string
Any idea how to improve and make it more denser
for i= 1: 10
if i==6
if exist('A_6', 'file') == 2
load A_6;
else
run Test
end
elseif i==7
if exist('A_7.mat', 'file') == 2
load A_7;
else
run Test
end
elseif i==8
if exist('A_8.mat', 'file') == 2
load A_8;
else
run Test
end
elseif i==9
if exist('A_9.mat', 'file') == 2
load A_9;
else
run Test
end
elseif i==10
if exist('A_10.mat', 'file') == 2
load A_10;
else
run Test
end
end
end
It is basically check if file is available, if the file is available load it otherwise run the Test file to get the values.

채택된 답변

Cedric
Cedric 2015년 7월 28일
편집: Cedric 2015년 7월 28일
The approach is questionable, but let's say that technically you can do this:
for k = 6 : 10
baseName = sprintf( 'A_%d', k ) ;
if exist( [baseName, '.mat'], 'file' )
load( baseName ) ;
else
run Test
end
end
PS: I used k instead of i, because we usually keep i and j for complex numbers. If your script Test uses i from the workspace though (which would not be a good practice), you will have to either use i as a loop index, or update the script so it uses k.
  댓글 수: 1
Hesham Ismail
Hesham Ismail 2015년 7월 28일
Thanks that made my code more cleaner

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by