Multiply specific parts of cell with cell column
3 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(6 个)
Adam
2016-10-24
编辑:Adam
2016-10-24
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 个评论
Andrei Bobrov
2016-10-24
编辑:Andrei Bobrov
2016-10-24
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 个评论
Alexandra Harkai
2016-10-24
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 个评论
Ki Loius
2016-10-24
编辑:Ki Loius
2016-10-24
2 个评论
Alexandra Harkai
2016-10-24
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
2016-10-24
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!