이 질문을 팔로우합니다.
- 팔로우하는 게시물 피드에서 업데이트를 확인할 수 있습니다.
- 정보 수신 기본 설정에 따라 이메일을 받을 수 있습니다.
replacing elements in a matrix of char
조회 수: 11 (최근 30일)
이전 댓글 표시
Is there a function similar to string replace for char's? For instance in the code below I would like to remove the element 'x' in "this" and then display it again without the x.
this = ['axaa'];
ans =
aaa
I am thinking I would possibly have to make an empty char array and then append to it? Thanks for any advice.
답변 (1개)
Image Analyst
2019년 11월 23일
Try this:
this = ['axaa'];
output = strrep(this, 'x', '') % One way
output = this(this ~= 'x') % Another way
댓글 수: 24
xRobot
2019년 11월 23일
I'm trying to run this:
scrambled = ['oodd'; 'haaa'; 'aaaa';];
disp(scrambled);
guess = input('Enter guess(any four letter word,you can choose letters from anywhere): ','s');
char = char(guess);
fprintf('\n');
for i = 1:1:4
index = char(i);
member = ismember(index,scrambled);
if member == 1
output = strrep(scrambled, index, ' '); % One way
end
end
disp(output);
I guess I need another for loop 1:1:12 but how do insert it?
xRobot
2019년 11월 23일
Error using strrep
Char inputs must be row
vectors.
But, 'index' is a row vector. In the workspace it is equal to 'some letter' with the char indication.
xRobot
2019년 11월 23일
I got it to work with the second solution, however it removed all of the a's when i typed in "nnna". Instead of just one.
xRobot
2019년 11월 23일
How can I check for multiple occurences of an a letter in:
scrambled = ['oodd'; 'haaa'; 'aaaa';];
xRobot
2019년 11월 23일
multiples = count(scrambled,index);
I have this, however I am not sure how to use it to my advantage.
Image Analyst
2019년 11월 23일
Well now I'm confused. Do you want to get rid of a whole word ("any four letter word"), or one or more letters within the words?
What is your current code?
If you delete letters such that your strings are not all the same length, you'll have to use cell arrays, not string arrays. For example
>> scrambled = ['oodd'; 'haaa'; 'aza';]
Dimensions of arrays being concatenated are not consistent.
is not allowed since "aza" is not 4 characters like all the other entries.
Walter Roberson
2019년 11월 23일
편집: Walter Roberson
2019년 11월 23일
char(regexprep(string(scrambled), 'a', ' ', 'once')) % Replace one 'a' with a space.
xRobot
2019년 11월 24일
scrambled = ['oodd'; 'haaa'; 'aaaa';];
disp(scrambled);
guess = input('Enter guess: ','s');
fprintf('\n');
for i = 1:1:4
index = guess(i);
member = ismember(index,scrambled);
if member == 1
char(regexprep(string(scrambled), index, ' ', 'once')); % Replace one 'a' with a space.
end
end
This is the code. It would be optimum to delete the entire phrase at once but I under the assumption it would not be possible to do so hence I tried implementing the for loop to traverse 'guess' looking for a match. Originally I had "charGuess = char(guess)" right after the input variable because I assumed the input was a string and I wanted to be able to index it but in the workspace it identifies "guess" as char so I guess this is not needed.
Image Analyst
2019년 11월 24일
char() is not being assigned to anything. You need to assign it to some variable, which you then check.
What do you expect as the output. For example if I enter "d" do you want to omit the first word from the output? Like this:
scrambled = {'oodd'; 'haaa'; 'aaaa'}
disp(scrambled);
guess = input('Enter guess: ','s')
fprintf('\n');
numWords = length(scrambled)
rowsToKeep = true(numWords, 1);
for k = 1 : length(scrambled)
thisWord = scrambled{k};
if contains(thisWord, guess)
rowsToKeep(k) = false;
end
end
output = scrambled(rowsToKeep)
Output in command window:
scrambled =
3×1 cell array
{'oodd'}
{'haaa'}
{'aaaa'}
Enter guess: d
guess =
'd'
numWords =
3
output =
2×1 cell array
{'haaa'}
{'aaaa'}
xRobot
2019년 11월 24일
Yes! This is what I am getting at but without removing all d's. Say for example the user found a four letter combination for the word "hood" and typed it in. I would like to remove the word hood only from the array and it would output with hood removed something like:
d
aaa
aaaa
I am also not sure why the above code also removed the two letter o's when guess was "d".
Image Analyst
2019년 11월 24일
It removed the entire string because you said "It would be optimum to delete the entire phrase" so that's what I did. Now I'm confused again. Explain in detail why, if the word is "oodd" and the guess word is "hood" how you end up with only a single "d". If you're only removing all but the last occurrence, then why is an "o" also not left behind? Why just the "d" is left behind?
xRobot
2019년 11월 24일
편집: Image Analyst
2019년 11월 24일
The "d" would be the only thing left behind as far as the top row because I would like to remove all the letters in the word "hood" from the block. "hood" contains "h" "o" "o" and a "d".
So, if I removed "h" two "o's" and a "d" from the block the resulting block would contain what is left minus "h" two "o's" and one "d" resulting in :
d
aaa
aaaa
which differs from the original block before the guess:
oodd
haaa
aaaa
I want to remove only the letters that make up the guess for however many occurences.
"o" occurs 2 times in the word "hood" so I need to remove two "o's". "h" occurs once so I need to take one "h" out of the block and so on and so forth.
Image Analyst
2019년 11월 24일
This will do it:
scrambled = {'oodd'; 'haaa'; 'aaaa'}
disp(scrambled);
% guess = input('Enter guess: ','s')
guess = 'hood';
fprintf('\n');
numWords = length(scrambled)
output = scrambled; % Initialize
for k = 1 : length(scrambled)
thisWord = output{k};
for k2 = 1 : length(guess)
thisLetter = guess(k2);
index = find(thisWord == thisLetter, 1, 'first')
thisWord(index) = '';
end
output{k} = thisWord; % Put back in the possibly altered word.
end
output % Show in command window.
xRobot
2019년 11월 24일
It did work for the word hood but for other combinations at the input it did not work as well.
For instance I enterd " daxx " at the input and it outputted:
'ood'
'haa'
'aaa'
Which means it removed it removed "d" once as it should but it removed " a " more than once.
Image Analyst
2019년 11월 24일
'haaa' went to 'haa', and 'aaaa' went to 'aaa' so to me it looks like it's removing "a" once per word. Why do you say it's removing more than 1 'a'?
xRobot
2019년 11월 24일
Ah yes it is going by word. I aim to remove "a" per the whole block of words. So if the guess has one "a" in it then remove only one a from the entire block.
Image Analyst
2019년 11월 25일
What do you mean by "block"? I done have any. I have character arrays (simple strings), and cell arrays (arrays of chracter arrays). Do you want to only remove the first occurrence of a character,in the first cell that it appears in, regardless of how many cells it appears in?
Please review the FAQ on cell arrays
xRobot
2019년 11월 25일
In reading documentation prior to this post I was under the assumption that a character array was an array of character vectors not "simple strings". As per the "block" I simply refer to the character as a block of letter because of the visual effect of a block it has when displayed in the command window. In your question concerning "first occurence", yes I would like to remove the first occurence in the first cell that a letter a letter appears in. However, if the word inputted is "good", in order to fully remove the word "good" from the combination of three cells I would have to remove it more than once because the word has two "o's" in it. Removing on the first occurence of "o" in the first cell that it appears in the case of "good" inputted would be no good for what I am trying to accomplish.
The user is playing a game. The user is presented a "block" of letters. The user is to search said block and try to find a four letter combination that makes a word. The user then types it in. Then it is removed from the block. If the word the user inputs is "good", then the program removes 1 "g", 2 "o's" and 1 "d". Then presents the resulting block to the user to find another four letter word etc.
xRobot
2019년 11월 25일
I have researched " count() " in order to keep track of the number of occurences of a particular letter and write code to remove it for however many times it occurs in the user "input" guess but I had trouble implementing it. I did did not exhaust this approach as I beleived that the task could be done without using this approach. Do you think that implementing " count() " could be a more effecient approach to what I am trying to accomplish. I did not want to waste my time with it because I thought that I was getting close with other methods. I have very little experience with Matlab as you can see but disecting your code and reading on the functions that use which I didn't know existed is helping me.
Image Analyst
2019년 11월 25일
I don't know - perhaps. I didn't even know that count function existed. But wonderful, now another built-in MATLAB function that uses a common name that we'll have to take care not to use as a variable name.
Walter Roberson
2019년 11월 26일
I would suggest that you should be considering using a "multiset". A multiset is similar to a set, except that each element has an associated count. A target word can still be formed if its multiset is a (multiset) subset of the available letters.
xRobot
2019년 11월 27일
Hmm sounds very interesting. So “multiset” would be the keyword in searching the documentation? I am going to investigate this further.
Walter Roberson
2019년 11월 27일
MATLAB itself does not have much support for multisets built in -- just some obscure parts of the internal symbolic engine, https://www.mathworks.com/help/symbolic/mupad_ref/dom-multiset.html . But multiset is the common mathematics term.
참고 항목
태그
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!오류 발생
페이지가 변경되었기 때문에 동작을 완료할 수 없습니다. 업데이트된 상태를 보려면 페이지를 다시 불러오십시오.
웹사이트 선택
번역된 콘텐츠를 보고 지역별 이벤트와 혜택을 살펴보려면 웹사이트를 선택하십시오. 현재 계신 지역에 따라 다음 웹사이트를 권장합니다:
또한 다음 목록에서 웹사이트를 선택하실 수도 있습니다.
사이트 성능 최적화 방법
최고의 사이트 성능을 위해 중국 사이트(중국어 또는 영어)를 선택하십시오. 현재 계신 지역에서는 다른 국가의 MathWorks 사이트 방문이 최적화되지 않았습니다.
미주
- América Latina (Español)
- Canada (English)
- United States (English)
유럽
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom(English)
아시아 태평양
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 日本Japanese (日本語)
- 한국Korean (한국어)