Matlab是否具有类似于strfind的功能 [英] Does Matlab have a function similar to strfind
问题描述
但是,如果String匹配,它不会返回仅一个索引,而是会根据单词的第一个字母返回搜索矩阵的元素?
But instead of returning just one index if the String matches, it returns the element of the searched matrix according to the word's first letter?
例如,如果我有一个20乘20的整数矩阵,并且该矩阵中包含的序列是:3、34、6、7、8,并说我是否在该矩阵中使用了strfind并在其中寻找一个相同的Ints字符串,它将返回其起始矩阵的列.但我也希望它也返回该行.
For example, if I had a 20 by 20 matrix of ints and contained within that matrix was the sequence: 3, 34, 6, 7, 8. and say if I used strfind with this matrix and was searching it for an identical String of Ints it would return the column of the matrix that it starts with. But I want it to return the row as well.
我最初是在想,因为我使用for循环来处理每一行,所以i的值将是该行,但是我在努力实现它吗?
I was initially thinking, because I use a for loop to process each row, the value of i will be the row, but I am struggling to implement it?
推荐答案
做一些数学运算. strfind
需要一个单行向量,您可以使用冒号运算符:
轻松实现这一点-然后使用该位置计算行索引和列索引.
Do some math. strfind
requires a single-row vector, you can easily achieve that with the colon operator :
- then you use the position to calculate row and column index.
示例数据:
A = char('a'+ randi(26,5,5) -1)
A =
ftyqa
foxuk
iijtt
cvodu
tojvj
现在看看'x'
的位置:
[m,n] = size(A);
pos = strfind(A(:)','x');
column = ceil(pos/m);
row = mod(pos-1,m)+1;
column =
3
row =
2
也请参阅regexpi
,可能会有所帮助,因为它还会返回最后一个字母的索引.
Also have a look at regexpi
, maybe helpful as it also returns the index of the last letter.
[start,end] = regexpi(A(:)','myWord')
要希望结束这种单词搜索算法的疯狂,请尝试以下这些人:
首先将您的char矩阵从1 to 26
转换为整数,也就是您实际要查找的单词.
First transform your char matrix to integers from 1 to 26
, also the words you're actually looking for.
示例:
A = reshape(1:25,5,5)'
A =
1 6 11 16 21
2 7 12 17 22
3 8 13 18 23
4 9 14 19 24
5 10 15 20 25
[m,n] = size(A)
序列,无论用什么词:
sequence = [8 9 10];
[~,I] = intersect(A,sequence)
序列的索引:
I = 8 9 10
最后检查其是否确实有效:
finally check if its actually a valid sequence:
dI = diff(sort(I))
validSequence = ( numel(sequence) == sum(dI)+1 ...
&& numel(sequence) <= mod(I(end)-1,m)+1 )
validSequence = 1
其他情况是:
sequence = [13 10 11];
validSequence = 0 %violates 1st condition
sequence = [9 10 11];
validSequence = 0 %violates 2nd condition
在接下来的步骤中,您需要fliplr
,flipud
,transpose
和我的答案
In the next steps you need fliplr
,flipud
,transpose
and my answer here to finish the algorithm.
这篇关于Matlab是否具有类似于strfind的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!