필터 지우기
필터 지우기

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
Fope Ayo
Fope Ayo 2018년 11월 20일
combinations - by this i just mean the one combination of ‘gc’
gcgc %this is two
cg % non significant
gccg % non significant
cgccg % this would equivalate to one gc sequence

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

답변 (1개)

Stephen23
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
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 CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by