필터 지우기
필터 지우기

how to conver a string to a array or matrix

조회 수: 2 (최근 30일)
reza hamzeh
reza hamzeh 2019년 12월 15일
편집: Stephen23 2019년 12월 15일
hi. i have a string. its something like a='[0 1;J 2]' . i want to convert this string to a array. but as u see there is a varible in the string (J) . how can i convert this string to array so that J changes to a varible too.
  댓글 수: 4
Turlough Hughes
Turlough Hughes 2019년 12월 15일
Does the following help? I generate a 3d matrix here and he different values of J.
% set J to temp value, NaN, and then find index
J=NaN;
data1=eval(a);
[row,col]=find(isnan(data1));
J = 0:0.1:10;
data = repmat(data1,[1 1 length(J)]);
data(row,col,:) = J;
(Assumes you've assigned the variable to J and that J appears only once). I'm guessing the string is coming from some sort of user input? This approach is definitely not ideal. Can you explain more about what you are trying to do overall?
reza hamzeh
reza hamzeh 2019년 12월 15일
it gets the info from user like this figure. user insert a hamiltonian matrix. it should have only 1 or 2 varibles till the program can plot the hamiltonian versus the varibles (after doing some calculations on the matrix). the user have to defind the varible and its range in the textbox varibles (the varible that it put it in hamiltonian matrix) .
error.jpg

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

채택된 답변

Stephen23
Stephen23 2019년 12월 15일
편집: Stephen23 2019년 12월 15일
You can easily avoid evil eval by using str2func:
>> a = '[0 1;J 2]';
>> v = 'J'; % comma-separated variables, e.g. 'J,K,L'
>> f = str2func(sprintf('@(%s)%s;',v,a));
>> f(4)
ans =
0 1
4 2
This approach is also likely to be more efficient if you will call this function repeatedly.

추가 답변 (2개)

Bhaskar R
Bhaskar R 2019년 12월 15일
J must be initialized scaler values,
J = 2; % assumed(must a single value 1x1 size)
a='[0 1;J 2]';
result = eval(a);

Turlough Hughes
Turlough Hughes 2019년 12월 15일
편집: Turlough Hughes 2019년 12월 15일
You can make a 3d matrix with the third dimensions being the same size as your range. You could then generate the results as follows:
range=1:10;
J=0;
temp=eval(a);
H=NaN(size(temp,1),size(temp,2),length(range)); % Preallocate space for data
ii=0;
for c=range
ii=ii+1; % Incrementing variable provides index for where to store in H on each iteration
J=c;
H(:,:,ii)=eval(a);
end
Here I have just assigned values to range but you should write some code to update the variable range according to user input, whether it be 1:10 or 0:0.1:10.

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by