# BSXFUN Vectorizing. How can I vectorize the function?

2 views (last 30 days)
Iman Choukari on 8 Mar 2021
Edited: Iman Choukari on 15 Mar 2021
%And this is what I have so far, but I'm still getting this error: Non-singleton dimensions of the two input arrays must match each other.
function [spikes_train, n_bins] = make_spikes_matrix(data,index1,index2,bin_size, n_neurons, lag, bias)
n_bins = floor(length(data(index1,index2).spikes)/20); % keep them all
spikes_train = zeros(n_neurons,n_bins);
spikes_train(1:n_neurons)= bsxfun(@plus,spikes_train(1:n_neurons,1:n_bins),...
data(index1,index2).spikes(1:n_neurons,1:(n_bins*bin_size)));
spikes_train = spikes_train(:,bias+1-lag:n_bins-lag);
end
##### 2 CommentsShowHide 1 older comment
Rik on 15 Mar 2021
@Iman Choukari Why do you attempt to edit away parts of your question? Are you trying to find out if I'm more stubborn than you? There is a copy of this question here. If you edit away your code again, I will probably put it in a comment myself.

Athul Prakash on 12 Mar 2021
Edited: Athul Prakash on 12 Mar 2021
Hi Iman,
bsxfun intends to apply @plus to elements of same index across the two input arrays. So in your call to bsxfun, the dimensions of the two input matrices must match exactly, but 1:n_bins and 1:n_bins*bin_size are mismatched.
What you are looking for may be achieved through a simple sum() call.
% For a 2D matrix A (MxN),
bin_size = 100;
for i=1:M
r = reshape(A(i,:), bin_size, []); % reshape i-th column into size (num_bins, ...)
spikes = sum(r); % sum 'r' along the first dimension, thus adding all elements of same bin.
end
If reshape is unfamiliar, you may check its doc:
If needed, the outer for-loop may also be vectorized, something like:
% For a 2D matrix A (MxN),
bin_size = 100;
A_new = reshape(M, bin_size, []); % reshapes A into 3-D with each bin now along 2nd dimension.
B = sum(A_new,2); % sum along the second dimension = along each bin.
B = squeeze(B); % gets rid of the second dimension of size 1.
Hope it helps!

### Categories

Find more on Logical in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by