Iterate thru each row on a Matrix and return the result on a vector

2 views (last 30 days)
Hello, this is the first question I'm asking here, after a couple of reading either in Matlab help, or the forum.
I haven't been able to get what I'm looking for.
So, I'm working with a set x = 213 x 9
I'd like to perfrom a function for each row, therefore it should be a vector of 213 x .
After that plot the final result vs the original data.
Example of DataSet
See attached image
Function to be performed
function KU = Kurtosis( y )
% % Kurtosis
T=size(y,1);
KU(1)=y(1);
for i=2:T
y_mean=mean(y(1:i));
y_std=std(y(1:i));
KU(i)=sum(((y(1:i))-repmat(y_mean,i,1)).^4)/((T-1)*y_std.^4);
end
end
I've tried the following:
Using for loop
Kurtosis_test = 0;
for i = 1:size(data(1:1,:))
for j = 1:size(data)
Kurtosis_test = Kurtosis(data(i:j,:))
end
end
Using rowfun
test = rowfun(Kurtosis,data)
Not enough input arguments.
Error in Kurtosis (line 3)
T=size(y,1);
Thanks in advance.

Accepted Answer

dpb
dpb on 28 Dec 2019
Edited: dpb on 29 Dec 2019
Don't need no steenkin' loops! This is MATLAB!!! :)
kurt=kurtosis(y.').';
Above uses the fact that most ML functions in general and kurtosis in particular are written to operate on matrices by column; hence the ".'" to transpose your row-oriented array to columns first, then to transform the result back to a column to match rows.
mean, std and friends all operate same way.
NB: all of these also have an optional DIM argument that can be used to avoid the explicit transpose by saying which dimension of the array to operate over. In this case you want to operate on rows which is second dimension so
kurt=kurtosis(y,[],2); % operate by rows, not default column
NB2: the [] placeholder, the DIM argument is the third, the second optional argument is a flag for bias correction (default is on). See
doc kurtosis
for details of this.
BTW, the answer to the original question because every once in a while it is necessary to loop over an array, would be something like
nr=size(y,1); % number rows in array
kurt=zeros(nr,1); % preallocate for result
for i=1:nr
kurt(i)=kurtosis(y(i,:)); % compute kurtosis over each row vector in turn
end
Obviously, the function called can be any that accepts a vector, not just kurtosis, I just used for simplicity to illustrate the calling syntax.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2016b

Community Treasure Hunt

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

Start Hunting!