Filter löschen
Filter löschen

Uneven data multiplication in Matlab

1 Ansicht (letzte 30 Tage)
Neesha
Neesha am 17 Jun. 2014
Beantwortet: Andrei Bobrov am 18 Jun. 2014
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

Akzeptierte Antwort

Star Strider
Star Strider am 17 Jun. 2014
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 Kommentare
Image Analyst
Image Analyst am 18 Jun. 2014
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 am 18 Jun. 2014
Interesting!
I think the delay with the vectorised approach is the overhead in repmat.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Andrei Bobrov
Andrei Bobrov am 18 Jun. 2014
out = bsxfun(@rdivide,NumberOfDishes,NumberOfLocations);

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Tags

Noch keine Tags eingegeben.

Community Treasure Hunt

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

Start Hunting!

Translated by