for loop vector multiplication

15 vues (au cours des 30 derniers jours)
jonas paludan
jonas paludan le 12 Mar 2017
Modifié(e) : Jan le 12 Mar 2017
i have this assigment:
Create a function that computes the cost of each item and returns it as a vector. Find an elegant and simple way to write the code using what you have learned about matrix and vector operations.
here's what i have come up with so far which is a not so elegant solution and only works for a specific size of matrix. in my script it has have more than 1 column and less than 4 columns:
function itemCost=computeItemCost(resourceItemMatrix,resourceCost)
if length(resourceItemMatrix)>1
A=sum(resourceItemMatrix(:,1).*reshape(resourceCost,length(resourceCost),1));
itemCost=A;
if length(resourceItemMatrix)>1
B=sum(resourceItemMatrix(:,2).*reshape(resourceCost,length(resourceCost),1));
C=sum(resourceItemMatrix(:,3).*reshape(resourceCost,length(resourceCost),1));
itemCost=[A,B,C];
if length(resourceItemMatrix)>3
D=sum(resourceItemMatrix(:,4).*reshape(resourceCost,length(resourceCost),1));
itemCost=[A,B,C,D];
end
end
end
end
I know there is a much simpler way to do this(perhaps a for-loop?), but just keep running my head against a wall when i try. help would be much appreciated.
  1 commentaire
Jan
Jan le 12 Mar 2017
"less than 4 columns"? 4 columns are accepted also, but 2 columns are not.

Connectez-vous pour commenter.

Réponse acceptée

Jan
Jan le 12 Mar 2017
Modifié(e) : Jan le 12 Mar 2017
Do you mean:
function itemCost = computeItemCost(resourceItemMatrix, resourceCost)
itemCost = resourceCost(:).' * resourceItemMatrix;
end
You check for length(resourceItemMatrix)>1 twice in your code. If resourceItemMatrix is a matrix, length() might not do what you expect. Prefer:
if size(resourceItemMatrix, 2) > 1
A simplification of your original code:
function itemCost = computeItemCost(resourceItemMatrix, resourceCost)
switch size(resourceItemMatrix, 2)
case {0, 2}
error('Unexpected input.'); % ???
case {1, 3, 4}
itemCost = resourceCost(:).' * resourceItemMatrix;
otherwise
itemCost = resourceCost(:).' * resourceItemMatrix(:, 1:4);
end
end
Or according to the text of the question:
function itemCost = computeItemCost(resourceItemMatrix, resourceCost)
n = size(resourceItemMatrix, 2);
if n >= 1 && n <= 4
itemCost = resourceCost(:).' * resourceItemMatrix;
else
error('Unexpected input.'); % Or whatever you need.
end
end

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by