Azzera filtri
Azzera filtri

Uneven data multiplication in Matlab

1 visualizzazione (ultimi 30 giorni)
Neesha
Neesha il 17 Giu 2014
Risposto: Andrei Bobrov il 18 Giu 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

Risposta accettata

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

Accedi per commentare.

Più risposte (1)

Andrei Bobrov
Andrei Bobrov il 18 Giu 2014
out = bsxfun(@rdivide,NumberOfDishes,NumberOfLocations);

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Tag

Non è stata ancora inserito alcun tag.

Community Treasure Hunt

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

Start Hunting!

Translated by