How to create variables using strings in an array?

조회 수: 5 (최근 30일)
J. Hu
J. Hu 2013년 9월 15일
str1={'x','trs','height','width'}
str2='db_xtr'
For example, I wanted to do:
for ivar=1:size(str1,2)
C_%str1%_%str2%=ivar^2+2
end
to get following variables:
C_x_db_xtr = 1^2+2
C_trs_db_xtr = 2^2+2
C_height_db_xtr = 3^2+2
C_width_db_xtr = 4^2+2
seems function "genvarname" would do something similar but do not know how to do it for my particular case.
Thanks...

채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2013년 9월 15일
  댓글 수: 1
J. Hu
J. Hu 2013년 9월 15일
편집: Azzi Abdelmalek 2013년 9월 29일
It works. Great. Thanks... Seems the main reason not being recommended is that it runs slowly.
str1={'x','trs','height','width'}
str2='db_xtr'
for ivar=1:size(str1,2)
eval(sprintf('C_%s_%s=%d^2+2',str1{ivar},str2,ivar))
end

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

추가 답변 (1개)

Andrei Bobrov
Andrei Bobrov 2013년 9월 15일
str1={'x','trs','height','width'}
str2='db_xtr'
input1 = [strcat(str1,'_',str2);num2cell((1:numel(str1)).^2+2)]
C = struct(input1{:})
  댓글 수: 2
J. Hu
J. Hu 2013년 9월 15일
Thanks... however this is not exactly the way I want. It may work for some case. But how about if I need to put this in a multiple level loops and so the variable would be a 1D vector, 2D matrix like C_%str1%_%str2%(ivar1,ivar2)=ivar1^2+ivar2+2.
Walter Roberson
Walter Roberson 2013년 9월 15일
Don't do that.
C{ivar1}{ivar2} = ... some matrix expression ...

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by