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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by