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!