BSXFUN Vectorizing. How can I vectorize the function?

2 ビュー (過去 30 日間)
Iman Choukari
Iman Choukari 2021 年 3 月 8 日
編集済み: Iman Choukari 2021 年 3 月 15 日
%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),...
spikes_train = spikes_train(:,bias+1-lag:n_bins-lag);
  2 件のコメント
Rik 2021 年 3 月 15 日
@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.


回答 (1 件)

Athul Prakash
Athul Prakash 2021 年 3 月 12 日
編集済み: Athul Prakash 2021 年 3 月 12 日
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.
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!


Community Treasure Hunt

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

Start Hunting!

Translated by