필터 지우기
필터 지우기

assigning numbers to string elements

조회 수: 9 (최근 30일)
KA
KA 2015년 11월 18일
편집: Stephen23 2016년 1월 31일
Hi I have the following which creates 2 strings called left and right from a single string with the positions shifted by a single element.
pep='abcd';
sizepep=size(pep);
left=pep(1:(sizepep(2)-1));
right=pep(2:(sizepep(2)));
% so in this example left=abc and right = bcd
% if I were to assign numerical values to letters - eg.
a=1;
b=2;
c=3;
d=4;
How do I turn these two strings (left and right) into vectors so I can add each element together?
left=[1 2 3];
right=[2 3 4];
sum=[3 5 7]
Thank you in advance for advice.
  댓글 수: 1
Walter Roberson
Walter Roberson 2015년 11월 25일
Please avoid naming a variable "sum" as that interferes with using the MATLAB routine named "sum"

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

채택된 답변

Tushar Athawale
Tushar Athawale 2015년 11월 25일
편집: Tushar Athawale 2015년 11월 25일
It is possible to map strings to numeric arrays based on the predefined character maps. The following code snippet can be used in your example:
% Setup map
map('a')=1;
map('b')=2;
map('c')=3;
map('d')=4;
% Automatic setup invere of map (from map)
letter=map>0;
mapi(map(letter))=char(find(letter));
left = 'abc';
right = 'bcd';
% map string to numeric array.
left_code = map(left)
right_code = map(right)
% You can also map numeric array to string
left_decode = mapi(left_code)
sm = left_code + right_code;
Thanks to Bruno Luong for suggesting this approach in one of his posts in the MATLAB newsgroup:
  댓글 수: 1
KA
KA 2016년 1월 30일
Hi thank you for taking the time to answer this question sorry my reply took so long. Your answer works! but I have another question. Currently both left and right are taking values from the same map. Is it possible to adjust the script to have two unique maps. For example each letter has two different values depending if it is left or right?

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

추가 답변 (1개)

Walter Roberson
Walter Roberson 2015년 11월 25일
[~, left_code] = ismember(left, 'abcd');
[~, right_code] = ismember(right, 'abcd');
sum_code = left_code + right_code

Community Treasure Hunt

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

Start Hunting!

Translated by