for loop vector multiplication
15 views (last 30 days)
Show older comments
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 Comment
Accepted Answer
Jan
on 12 Mar 2017
Edited: Jan
on 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
0 Comments
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!