how to assign a variable using a string

조회 수: 51 (최근 30일)
Michael
Michael 2013년 4월 1일
I have a set of variables called "error1", "error2", etc.
Each is a 4D matrix and I want to extract certain parts of them for comparison, for example I'd like to plot the vector mean(errori(1,:,1,1)), where i = 1,2,...
How can I do this? I've tried using
for i = 1:10
a = sprintf('error%s',num2str(i));
b(i) = mean(a(1,:,1,1));
end
But that just sets a equal to a string, not the actual variable! Is there some function I can use that makes MATLAB recognise a string as a variable with the same name?
Thanks Mike

답변 (2개)

Walter Roberson
Walter Roberson 2013년 4월 1일
  댓글 수: 2
Ahmed A. Selman
Ahmed A. Selman 2013년 4월 2일
The task was (how to assign a variable using a string). I not sure if the question mentioned (using cells) anywhere?!
Walter Roberson
Walter Roberson 2013년 4월 2일
Q: "I want to learn how to cut glass so I can unlock this door that I can't push open!"
A: "Did you try pulling it instead?"
Showing people alternatives to avoid their problems in the first place is a valid answer.
Besides, FAQ does show the (not-recommended!) eval() solution.

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


Ahmed A. Selman
Ahmed A. Selman 2013년 4월 1일
Try (genvarname) with (eval) functions. Example (alter the example below to your use, i.e., instead of eval([b]) use eval([b = 'some_function(i)']) ):
clear
clc
error1=eye(3,3);
error2=eye(3,3)*2;
error3=eye(3,3)*3;
for i = 1:3
a = sprintf('error%s',num2str(i));
b = genvarname(a);
eval([b])
end
.. etc.
  댓글 수: 1
Jan
Jan 2013년 4월 2일
Do not use the EVAL approach. You find too many people here in the forum who got too many problems by this.

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

카테고리

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