Uneven data multiplication in Matlab

4 次查看(过去 30 天)
I have following
Data.numberOfDishes
Data.numOfLocations
As follows
numberOfDishes numberOfLocations
3 [1, 2, 4]
4 [9, 8, 5]
6 [11, 1, 9]
7 [2, 3, 4]
9 [7, 7, 7]
I want to have resulting column 'total' by doing numberOfDishes/each element of numberOfLocations
For example, so that 'total' for first row would be [3/1, 3/2, 3/4]
i know '.' would not work. mrdivide does not seem an option. Can i do this without having to create numberOfDishes of the same size as numOfLocations

采纳的回答

Star Strider
Star Strider 2014-6-17
This works:
NumberOfDishes = [3 4 6 7 9];
NumberOfLocations = [1, 2, 4; 9, 8, 5; 11, 1, 9; 2, 3, 4; 7, 7, 7];
for k1 = 1:length(NumberOfDishes)
Total(k1,:) = NumberOfDishes(k1)./NumberOfLocations(k1,:);
end
% To express them as fractions:
Total = rats(Total)
  4 个评论
Image Analyst
Image Analyst 2014-6-18
Let's compare the "vectorized" approach with the brute force "for loop" approach:
NumberOfDishes = [3; 4; 6; 7; 9]
NumberOfLocations = [1, 2, 4; 9, 8, 5; 11, 1, 9; 2, 3, 4; 7, 7, 7]
tic
for k1 = 1:length(NumberOfDishes)
Total(k1,:) = NumberOfDishes(k1)./NumberOfLocations(k1,:);
end
toc
% To express them as fractions:
Total
Total = rats(Total)
% Use a "vectorized" approach.
tic
t = repmat(NumberOfDishes(:), [1, size(NumberOfLocations, 2)]) ./ NumberOfLocations
toc
Results in command window:
Elapsed time is 0.000032 seconds.
Elapsed time is 0.000402 seconds.
Hmmmm.... Looks like the for loop is 12 times faster.
Star Strider
Star Strider 2014-6-18
Interesting!
I think the delay with the vectorised approach is the overhead in repmat.

请先登录,再进行评论。

更多回答(1 个)

Andrei Bobrov
Andrei Bobrov 2014-6-18
out = bsxfun(@rdivide,NumberOfDishes,NumberOfLocations);

类别

Help CenterFile Exchange 中查找有关 Whos 的更多信息

标签

尚未输入任何标签。

Community Treasure Hunt

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

Start Hunting!

Translated by