how to use string in eval function

조회 수: 6 (최근 30일)
Ham Man
Ham Man 2022년 8월 29일
댓글: Image Analyst 2022년 8월 29일
I'd like to use eval for this expression: sheet ='p1_Q1_test';
It works for num2str(x) but does not work for string y.
How can I use the string 'y' correctly in eval?
x = 1;
y = 'Q1';
eval(['sheet =p' num2str(x) '_' y '_final']);
A = xlsread('E:\myfolder\datasheet.xlsx', sheet);
error:
Undefined function or variable 'p1_Q1_test'.

답변 (2개)

KSSV
KSSV 2022년 8월 29일
x = 1;
y = 'Q1';
sheet =strcat('P',num2str(x),'_',y,'_final')
sheet = 'P1_Q1_final'

Stephen23
Stephen23 2022년 8월 29일
이동: Image Analyst 2022년 8월 29일
"I'd like to use eval for this expression: sheet ='p1_Q1_test';"
Why write such complex code?
x = 1;
y = 'Q1';
sheet = ['p',num2str(x),'_',y,'_final']
sheet = 'p1_Q1_final'
or even better using SPRINTF:
sheet = sprintf('p%d_%s_final',x,y)
sheet = 'p1_Q1_final'
  댓글 수: 2
Ham Man
Ham Man 2022년 8월 29일
이동: Image Analyst 2022년 8월 29일
Great thanks. It works nice!
Image Analyst
Image Analyst 2022년 8월 29일
@Ham Man then please click the "Accept this answer" link to award @Stephen23 "reputation points". He'll appreciate it. Thanks in advance. 🙂

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by