Applying a function to each row vector of a matrix

조회 수: 30 (최근 30일)
Sameer Karim
Sameer Karim 2018년 4월 7일
댓글: Sameer Karim 2018년 4월 7일
I have a function that I want to apply to each row of a 7800x784 matrix. The function returns a scalar and puts it into a 7800x1 matrix. So, each row of the first matrix is computed one by one and the output is sent to the second matrix. s and Ns are both 1x26 matrix. Following is my function:
function [ind] = naive_bayes(X, s, Ns)
prob = zeros(1,26);
x = 1;
y = 1800;
for i = 1:size(s,2)
like = sum(X(x:y,:))/s(1,i);
prob(1,i) = Ns(1,i) * prod((like.^X).* (1-like).^(1-X));
x = y + 1;
y = y +1800;
end
[~,ind] = max(prob);
end
Thank you!

답변 (1개)

Walter Roberson
Walter Roberson 2018년 4월 7일
편집: Walter Roberson 2018년 4월 7일
result = arrayfun(@(ROWIDX) naive_bayes(YourArray(ROWIDX,:)), (1:size(YourArray,1)).');
However, your function has the difficulty that it uses x and y and s without those having been defined.
  댓글 수: 3
Walter Roberson
Walter Roberson 2018년 4월 7일
result = arrayfun(@(ROWIDX) naive_bayes(YourArray(ROWIDX,:),s,Ns), (1:size(YourArray,1)).');
Sameer Karim
Sameer Karim 2018년 4월 7일
I think i messed up the transistion as naive_bayes was actually a part of my main code. I want to reorganise my question so this is the code that i initially had.
prob = zeros(1,26);
for jj = 1:N
for i = 1:size(s,2)
like = sum(X(x:y,:))/s(1,i);
prob(1,i) = Ns(1,i) * prod((like.^Xtst(jj,:)).* (1-like).^(1- Xtst(jj,:)));
x = y + 1;
y = y +1800;
end
x = 1;
y = 1800;
[~,ind] = max(prob);
Cpreds(jj,1) = ind;
end
Here Xtst is my 7800x784 array with N being 7800. X is a 48600x784 array, so sum forms a 1x784 matrix. prob is processed size(s, 2)xN times, x and y resets to its initial values after one row of Xtst is processed. Now Cpreds is my Nx1 matrix with i want to finally produce. So the previous functions was actually being applied on each row of Xtst. Since the matrix size is huge I wanted to implement it using vectorisation. Thanks in advance!

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

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by