フィルターのクリア

How to assign a value against a string from 1st column to other?

3 ビュー (過去 30 日間)
Muhammad Imran
Muhammad Imran 2020 年 4 月 17 日
コメント済み: Muhammad Imran 2020 年 4 月 24 日
Hi Everyone,
I have to write a code in which i can get an input from user and then this input can read from a table and pick a value against the user input.
My table is excel file and have these two columns as X and Z.
For example if user gives input from as 2A then value of Z assigned should be Z=0.15.
Similarly for user input 2B z should be Z=0.2.
Kind Regards.

採用された回答

Cris LaPierre
Cris LaPierre 2020 年 4 月 18 日
編集済み: Cris LaPierre 2020 年 4 月 18 日
If you create your table as a MATLAB table with your X values as the rownames, you could do the following:
X = {'1';'2A';'2B';'3';'4'}';
Z = [0.075, 0.15, 0.2, 0.3, 0.4]';
zTbl = table(Z,'RowNames',X);
You could then prompt your user to enter a value for x, and then use that to extract the corresponding value for Z.
x = input("Enter a value for x: ","s")
Z = zTbl{upper(x),"Z"}
See this doc page on why I'm using curly braces to index into zTbl.
  2 件のコメント
Cris LaPierre
Cris LaPierre 2020 年 4 月 18 日
If you are interested in how to create this table importing the data from Excel, see my answer to your post on that.
Muhammad Imran
Muhammad Imran 2020 年 4 月 24 日
Thank you the above code worked.

サインインしてコメントする。

その他の回答 (1 件)

Kevin Hellemans
Kevin Hellemans 2020 年 4 月 17 日
Hi,
The fastest way would be to create a Matlab variable directly. However, should you want to create a dynamic link to an Excel file, the following code may help.
First, I created an Excel file 'MyWorkBook':
% Read data from Excel
XLSTable = readtable('MyWorkBook.xlsx'); %if headers are set correctly, this function will create a table with X and Z columns
% Request info from user
UserValue = inputdlg('Please Provide X','Matlab Answers');
% Look Up Value in Table
idx = cellfun(@(x) strcmpi(x,UserValue{1}),XLSTable.X);
% Report Results
if sum(idx) == 1
msgbox(['Z Value: ' num2str(XLSTable.Z(idx))])
Z = num2str(XLSTable.Z(idx));
elseif sum(idx) == 0
msgbox(['Value not found'])
elseif sum(idx) > 1
msgbox(['Multiple Values found'])
Z = num2str(XLSTable.Z(idx));
end
I hope this helps!
Kevin
  3 件のコメント
Kevin Hellemans
Kevin Hellemans 2020 年 4 月 17 日
Hi,
I've tested it on my system with 2A and 2B as well, both are working. Since the function reads the first columns as strings, it should not matter. The readtable was introduced in R2013b, so it should work, regular tables as well. Can you provide more details as to what is not working? What kind of feedback to you get?
Kevin
Muhammad Imran
Muhammad Imran 2020 年 4 月 18 日
It is showing value not found dialog box for 2A value and 2B.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeSpreadsheets についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by