How can I create a function which takes a matrix of characters as the input and outputs the number of specific characters within that matrix?
1 次查看(过去 30 天)
显示 更早的评论
I am looking for a function, not an equation or anything else that may be simpler.
I have the following sequence (matrix)
bases = [ 't' 't' 'a' 'c' 'a' 'a' 't' 'g' 'g' 'a' 'g' 't' 'a' 'a' 'g';...
'a' 'g' 't' 'a' 'a' 'c' 'c' 'a' 'c' 'g' 'c' 't' 'a' 't' 'c';...
'a' 'c' 'c' 'c' 'g' 'g' 'a' 'a' 'a' 'a' 'a' 't' 'c' 'c' 'c';...
'a' 'c' 'a' 't' 'c' 'c' 'c' 'c' 'c' 'c' 't' 't' 'g' 't' 'g' ]
I need the functuon to input a matrix like above but not specifically that matrix, that is just an example, it has to work for multiple sequences.
The output must be the number of 'gc' combinations within the sequence.
I have tried
function [ GCRatio ] = func3( B )
GCRatio = numel(strfind (B,'gc'))
end
though this has not worked
3 个评论
回答(1 个)
Stephen23
2018-11-20
编辑:Stephen23
2018-11-20
Two methods to count the exact sequence 'gc' on each line of the character matrix.
Method one: convert to cell array, use strfind and cellfun:
>> cellfun(@numel,strfind(num2cell(bases,2),'gc'))
ans =
0
1
0
0
It is easy to make this into a function:
>> fun = @(m)cellfun(@numel,strfind(num2cell(m,2),'gc'));
>> fun(bases)
ans =
0
1
0
0
Method two: logical arrays and sum:
>> sum(bases(:,1:end-1)=='g' & bases(:,2:end)=='c',2)
ans =
0
1
0
0
This is also easy to make into a function:
>> fun = @(m) sum(m(:,1:end-1)=='g' & m(:,2:end)=='c',2);
>> fun(bases)
ans =
0
1
0
0
3 个评论
Stephen23
2018-11-20
编辑:Stephen23
2018-11-20
"This is the equation overall, so in coding the function what exactly do I write?"
I already gave you two examples of functions, both named fun in my answer :
I do not know what you mean by "equation" in relation to the functions that I gave you.
You do not need to put those anonymous functions inside another function to use them: they are already functions, so you can just call them like any other function, using the name fun. I showed you this in my answer.
However if you really want to write a main/local/nested function, then just get rid of the anonymous function definition and call the cellfun directly:
function out = myfunction(m)
out = cellfun(@numel,strfind(num2cell(m,2),'gc'));
end
You can read about different function types here:
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!