for loop vector multiplication

조회 수: 15 (최근 30일)
jonas paludan
jonas paludan 2017년 3월 12일
편집: Jan 2017년 3월 12일
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