How do i call a value from a matrix based on an input?

2 views (last 30 days)
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.

Answers (1)

Anay
Anay on 30 Jun 2025
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:

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!