Effacer les filtres
Effacer les filtres

Uneven data multiplication in Matlab

1 vue (au cours des 30 derniers jours)
Neesha
Neesha le 17 Juin 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

Réponse acceptée

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

Connectez-vous pour commenter.

Plus de réponses (1)

Andrei Bobrov
Andrei Bobrov le 18 Juin 2014
out = bsxfun(@rdivide,NumberOfDishes,NumberOfLocations);

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Tags

Aucun tag saisi pour le moment.

Community Treasure Hunt

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

Start Hunting!

Translated by