Multiply specific parts of cell with cell column
3 views (last 30 days)
Show older comments
How can I multiply specific parts of a cell array with a cell column?
e.g. y is a 3x5 cell
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
I want to multiply the y(2:3,2:3) party with y(2:3,5)
16 17 * 19
21 22 24
result should a 2x2 array:
16*19 17*19
21*14 22*14
My attempt did not work:
x = zeros(3,2); %create new empty array (first line should be empty)
for i=2:3
x(i,:)=cell2mat(y(i,2:5)).*cell2mat(y(i,5)));
end
0 Comments
Answers (6)
Adam
on 24 Oct 2016
Edited: Adam
on 24 Oct 2016
Why do you have a cell array in the first place instead of a numeric array? It is far slower and requires you to use much uglier constructs to do simple maths operations.
y(2:3,2:3) = y(2:3,2:3) .* y(2:3,5);
would work on a numeric array (in R2016b - Andrei Bobrov's alternative is what I always used pre-R2016b)
y = cell2mat( y );
before that will allow you to get away from your cell array.
0 Comments
Andrei Bobrov
on 24 Oct 2016
Edited: Andrei Bobrov
on 24 Oct 2016
y1 = {10 11 12 13 14
15 16 17 18 19
20 21 22 23 24};
y = cell2mat(y1);
out = y(2:3,2:3).*y(2:3,5); % R2016b and Octave
out = bsxfun(@times,y(2:3,2:3),y(2:3,5)); % R2016a and before
0 Comments
Alexandra Harkai
on 24 Oct 2016
There could be a typo here:
cell2mat(y(i,2:5))
Probably should be:
cell2mat(y(i,2:3))
So result should be:
16*19 17*19
21*24 22*24
This can be achieved like this, without a loop (see https://uk.mathworks.com/help/matlab/ref/bsxfun.html):
x = zeros(3,2); %create new empty array (first line should be empty)
x(2:3,:) = bsxfun(@times, cell2mat(y(2:3,2:3)), cell2mat(y(2:3,5)));
0 Comments
Ki Loius
on 24 Oct 2016
Edited: Ki Loius
on 24 Oct 2016
2 Comments
Alexandra Harkai
on 24 Oct 2016
Since the example x array was initialised as an all-0 array, it looked like you wanted a numerical array. If that's not the case, you can always do num2cell(...) before the assignment.
Adam
on 24 Oct 2016
It's generally a very bad idea to have data structured in that way with a row and column like that (a table structure sounds more obvious if that is what you want), but you can still apply any of the solutions given with a bit of alteration.
Just pull out the part of the array you want and apply to that, then re-insert it, using num2cell and cell2mat either side of your operation and depending whether you have R2016b or not use bsxfun to do the multiplication.
See Also
Categories
Find more on Matrix Indexing 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!