for loop vector multiplication

15 次查看(过去 30 天)
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 个评论
Jan
Jan 2017-3-12
"less than 4 columns"? 4 columns are accepted also, but 2 columns are not.

请先登录,再进行评论。

采纳的回答

Jan
Jan 2017-3-12
编辑:Jan 2017-3-12
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 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by