简体   繁体   English

如果只知道总成本,如何编写脚本来查找列表中每个项目的成本? MATLAB

[英]How do I write a script to find the cost of each item in a list if only the total cost is known? MATLAB

I am trying to write a script in MATLAB for my class.我正在尝试在 MATLAB 中为我的班级编写脚本。 The scenario is that there are four different types of pens.场景是有四种不同类型的笔。 I only know the total cost of all four pens (total is not actually given to me).我只知道所有四支笔的总成本(实际上并没有给我总数)。 I am trying to find the individual cost of each different type of pen.我试图找到每种不同类型笔的单独成本。 My 3 "friends" also each bought the four pens themselves.我的三个“朋友”也各自买了四支钢笔。 That makes for a total of 16 pens among 4 people.这使得 4 个人总共有 16 支笔。 Everyone's total cost should be the same.每个人的总成本应该是一样的。 The book suggests creating a matrix for the pens made up of columns for each different type of pen and rows for each of the people (4x4).这本书建议为笔创建一个矩阵,该矩阵由每种不同类型笔的列和每个人的行 (4x4) 组成。 It also says to have a column vector for the totals each person spent on the pens, which I presume would all be the same.它还说有一个列向量来表示每个人在笔上花费的总数,我认为这都是一样的。 I am stuck and really not sure how to go about solving this since I do not know the cost of even one of the pens.我被卡住了,真的不知道如何解决这个问题,因为我什至不知道其中一支笔的成本。 Any help would greatly be appreciated.任何帮助将不胜感激。

@TTT is right, linear algebra solves your task. @TTT 是对的,线性代数可以解决您的任务。 The great thing about Matlab is, that it can actually calculate linear algebra without the fuzz of building for-loops. Matlab 的伟大之处在于,它实际上可以计算线性代数,而无需构建 for 循环。 Here is a simple example that should suit your case.这是一个适合您情况的简单示例。

Footnote: Note that the matrix inversion with inv() will be flagged as inefficient by the Matlab-IDE (ie the program) because it is much faster and more accurate to calculate inv(NumPens) * total jointly (which is expressed as NumPens\\total ) than explicitly calculating the inverse of the matrix first -- but to teach linear algebra, this way is much better!)脚注:请注意,使用inv()进行矩阵求逆将被 Matlab-IDE(即程序)标记为低效,因为联合计算inv(NumPens) * total (表示为NumPens\\total ) 而不是先明确计算矩阵的逆——但是为了教授线性代数,这种方式要好得多!)

total = [17;13;12;27]; % vector 4x1 (number of persons x 1)

NumPens = [1 1 3 1
           1 0 1 1
           0 1 0 2
           3 0 1 1]; % matrix 4x4 (number of persons x number of pen types)

% total = NumPens * x % original system
x = inv(NumPens) * total % how to calculate the number of pens

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM