error in eval command

조회 수: 3 (최근 30일)
Mudasir Ahmed
Mudasir Ahmed 2014년 10월 1일
댓글: Mudasir Ahmed 2014년 10월 1일
clear all clc
a=[12 2 10 20 1 20]; b=[5 21 4 1 4 5]; c=[23 18 13 10 13 17]; d=[8 3 14 6 19 1];
for x=1:6 eval(sprintf('ch%d=[a(1,x) b(1,x) c(1,x) d(1,x)]',x)); end
for y=1:6 eval(sprintf('obj%d=[ch%d(1,1)+(2*ch%d(1,2))+(3*ch%d(1,3))+(4*ch%d(1,4))-30]',y)); end
output of first loop (correct response) ch1 = 12 5 23 8 ch2 = 2 21 18 3 ch3 = 10 4 13 14 ch4 = 20 1 10 6 ch5 = 1 4 13 19 ch6 = 20 5 17 1
in above program, matlab execute and return correct response of first loop, but give error in second loop (Error: This statement is incomplete. ) i want to execute following instruction using eval function for all ch1ch2.....ch6 variables, e.g ch1=[12 5 23 8] a=12 b=5 c=23 d=8 obj=a+2b+3c+4d-30
kindly help me. thanx in advance
  댓글 수: 1
Oleg Komarov
Oleg Komarov 2014년 10월 1일
편집: Oleg Komarov 2014년 10월 1일
Just do NOT use eval(). You are building a nightmare for yourself as the example code proves.

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

채택된 답변

Thorsten
Thorsten 2014년 10월 1일
for y=1:6
eval(sprintf('obj%d=[ch%d(1,1)+(2*ch%d(1,2))+(3*ch%d(1,3))+(4*ch%d(1,4))-30]',[y y y y y]));
end
  댓글 수: 2
Mudasir Ahmed
Mudasir Ahmed 2014년 10월 1일
thanx sir, its working :) sir can u defined why you have used [y y y y y]. i got it little bit, i think as equation contain 5 terms a+2b+3c+4c-30 thts why u have used a matrix of 5 y. kindly explain it logically , thanx again sir
Mudasir Ahmed
Mudasir Ahmed 2014년 10월 1일
i got it sir. in eval command %d sign is 5 times used, that's why we have to make a matrix of 5 y.

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

추가 답변 (1개)

Michael Haderlein
Michael Haderlein 2014년 10월 1일
To archieve this obj array, you can do the following:
a=[12 2 10 20 1 20]; b=[5 21 4 1 4 5]; c=[23 18 13 10 13 17]; d=[8 3 14 6 19 1];
ch=cat(1,a,b,c,d)';
obj=ch*(1:4)'-30;
Alternatively, you define a,b,c,d as column vectors and concatenate along the second dimension without transposing. In any case, this is the way you should do it in Matlab.
  댓글 수: 1
Mudasir Ahmed
Mudasir Ahmed 2014년 10월 1일
thanx sir. it is also working :)

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

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by