How do i call a value from a matrix based on an input?
조회 수: 2 (최근 30일)
이전 댓글 표시
My program must calculate the total cost by using the variable PN to select the correct part cost in the parts cost matrix PC. The total cost is the number of parts multiplied by the cost of each part.
How would I go about completing this?
So far I have this.
clc
clear
PC=[1741 2377 3203 3571;0.37 0.21 0.31 0.17];%first row indicates the part number. Second row corresponds to the cost of each part.
C=input('Enter company name: ','s');
PN=menu('Select a part number',PC(1,1),PC(1,2),PC(1,3),PC(1,4));
Q=input('Enter quantity of the selected part: ');
fprintf('An order has been placed by %s for %d parts.',C,Q);
fprintf('Each part costs %0.1f.',
Also, im not sure if there is a better way of writing out the following statement:
PN=menu('Select a part number',PC(1,1),PC(1,2),PC(1,3),PC(1,4));
Thanks in advance.
댓글 수: 0
답변 (1개)
Anay
2025년 6월 30일
Hi KR,
You can consider using “dictionary” instead of matrix since you are mapping cost to each part number. Dictionary is a datatype which allows us to lookup data mapped to a key. Since you want to lookup costs for a given part number, part numbers should be the “key”. Consider following the below link for more information on using the “dictionary” datatype in MATLAB.
Also, the use of “menu” is not recommended by the MATLAB documentation. You should consider using “listdlg” instead of “menu” method. “listdlg” creates a list-selection dialog box just like the “menu” method. You can use the below code for reference:
partNumbers = [1741 2377 3203 3571];
partCosts = [0.37 0.21 0.31 0.17];
prodDict = dictionary(partNumbers, partCosts);
PN=listdlg('PromptString','Select a part number','SelectionMode',...
'single','ListString',string(partNumbers));
Q=input('Enter quantity of the selected part: ');
cost = prodDict(partNumbers(PN)) * Q;
fprintf('Cost of the part is %f\n', cost);
You can find more information about “listdlg” in MATLAB documentation by following the below link:
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!