You are now following this question
- You will see updates in your followed content feed.
- You may receive emails, depending on your communication preferences.
how to use ismember() to check if an inputted number exists in a matrix.
18 views (last 30 days)
Show older comments
I have a csv file named "NaiveBankData.csv" (attached) and i imported it, then read it as a matrix, but now how can i check if an inputted number exists in the first colomn of the matrix or not.
the code i used for the first step is:
%import file
importdata('NaiveBankData.csv');
%read file as matrix
readNaiveBankData=readmatrix('NaiveBankData.csv', 'ThousandsSeparator', ',');
then i need to use:
%inputted number
AN = input('Enter account number');
if AN exists in the first colomn of "readNaiveDataBank"
How do i do this last part in code?
1 Comment
Accepted Answer
DGM
on 3 Dec 2021
This might be a start:
% read file as table, since a matrix can't hold both datatypes
Data = readtable('NaiveBankData.csv');
% inputted number
AN = input('Enter account number: ');
accountexists = ismember(AN,Data.AccountNumber);
if accountexists
accountbalance = Data.Balance(AN==Data.AccountNumber)
end
If you want to do it all with numeric data, you'll have to deal with the fact that the file contains currency data with literal formatting. This can be done using other import tools, but I'm just going to post-process the text in the table.
% read file as table, since a matrix can't hold both datatypes
Data = readtable('NaiveBankData.csv');
% convert to numeric arrays
account = Data.AccountNumber;
balance = cellfun(@(x) x(all(x~=('£,')',1)),Data.Balance,'uniform',false);
balance = str2double(balance);
% inputted number
AN = input('Enter account number: ');
accountexists = ismember(AN,account);
if accountexists
accountbalance = balance(AN==account)
end
26 Comments
Tariq Hammoudeh
on 3 Dec 2021
Edited: Walter Roberson
on 3 Dec 2021
Thank you for that, the first part did work but for the second part i need something else.
My code is:
%import file
importdata('NaiveBankData.csv');
%read file as table
Data=readtable('NaiveBankData.csv');
%inputted number
AN = input('Enter account number');
accountValid= ismember(AN, Data.AccountNumber);
%check if the inputted account number exists in the csv file
if accountValid;
% give option to withdraw, deposit,etc...
transactionType= input('1:withdraw 2:deposit 3:account balance 4:end use');
switch transactionType
case 1
%if withdraw chosen
withdrawAmount = input ('Enter amount to Withdraw')
%check if there are insuffiecient funds in the account balance.
if withdrawAmount + 1.5 > accountBalance
disp('insufficient funds, enter a different amount')
%if there are suffiecient funds
elseif withdrawAmount + 1.5 <= accountBalance
continue....
end
what im doing, is designing an ATM machine with user interaction through the command line.
Now I cant figure out how to make it so that after a valid account number has been entered (valid meaning it exists in the .csv file) the program gets the account balance that matches the entered account number.
So help with this part would be highly appreciated.
Walter Roberson
on 3 Dec 2021
idx = find(Data.AccountNumber == AN);
accountValid = ~isempty(idx);
if accountValid
account_balance = Data(idx).Balance;
end
Tariq Hammoudeh
on 3 Dec 2021
Thank you, but what I need to do first is check if the inputted account number
"AN = input('Enter account number');" exists in the csv file using the code you showed me
" accountexists = ismember(AN,Data.AccountNumber);
if accountexists "
then i need to check if the inputted withdraw amount
" withdrawAmount = input ('Enter amount to Withdraw')" is greater than the corresponding balance.
is that possible to do in code?
Walter Roberson
on 3 Dec 2021
idx = find(Data.AccountNumber == AN);
accountValid = ~isempty(idx);
replaces the ismember() test.
After that my code pulls out the account balance. You can then compare the account balance to the amount to withdraw.
Tariq Hammoudeh
on 3 Dec 2021
Ok, but after I do this i get the following error.
Error using Matlab (line 31)
Subscripting into a table using one subscript (as in t(i)) or three or more subscripts (as in
t(i,j,k)) is not supported. Always specify a row subscript and a variable subscript, as in
t(rows,vars).
Line 31 is " account_balance = Data(idx).Balance"
DGM
on 3 Dec 2021
If you want to actually operate on the balance, you'll need to convert it to a numeric format.
%import file
%importdata('NaiveBankData.csv'); % this doesn't do anything
%read file as table
Data=readtable('NaiveBankData.csv');
% convert balance to numeric data
balance = cellfun(@(x) x(all(x~=('£,')',1)),Data.Balance,'uniform',false);
Data.Balance = str2double(balance);
%inputted number
AN = input('Enter account number '); % use some trailing space
idx = find(Data.AccountNumber == AN);
accountValid = ~isempty(idx);
%check if the inputted account number exists in the csv file
if accountValid
% give option to withdraw, deposit,etc...
transactionType = input('1:withdraw 2:deposit 3:account balance 4:end use ');
switch transactionType
case 1
%if withdraw chosen
withdrawAmount = input ('Enter amount to Withdraw ')
%check if there are insufficient funds in the account balance.
if withdrawAmount + 1.5 > Data.Balance(idx)
disp('insufficient funds, enter a different amount ')
% this does nothing
elseif withdrawAmount + 1.5 <= Data.Balance(idx)
Data.Balance(idx) = Data.Balance(idx) - (withdrawAmount + 1.5)
% do whatever message
end
case 2
% do deposit
case 3
% do balance
end
else
% do something if account isn't valid
end
Note that if you want to force the user to re-enter a value (an account number or withdrawal amount), you'll need to do it within a loop.
Tariq Hammoudeh
on 4 Dec 2021
Thank you soo much that really helped,
but i just want to ask, does this update the new table of balance that we created.
Data.Balance(idx) = Data.Balance(idx) - (withdrawAmount + 1.5)
if so, is there a way to update the actual csv file, rather than updating the new balance table.
DGM
on 4 Dec 2021
It would probably be easier to do all the work necessary on the table and then write the complete updated table to a file when done. Something like writetable() should be simple enough for the task.
Tariq Hammoudeh
on 4 Dec 2021
Ok so the only way to do that is to write a new table then export it to a new file??
But i need to be able to update the csv file, everytime a transaction occurs.
So is there a way to update the file or atleast the full table that we got with:
Data=readtable('NaiveBankData.csv');
Walter Roberson
on 4 Dec 2021
csv files are text files.
MATLAB was only ever supported on one operating system that permitted updating a line in the middle of a text file (DEC Vax VMS), and that operating system had two ways of managing files but MATLAB only ever supported the other way of managing files on that operating system. So MATLAB has never supported updating a line in the middle of a text file on any operating system.
Text files are stored as streams of bytes, with operating-system-specific bytes indicating end-of-line. (MS Windows historically required both Carriage Return and Line Feed to mark the end of a line, but these days also supports using only Line Feed to mark the end of a line; Linux has only ever supported Line Feed to mark the end of a line; in old old times, Mac supported only using Carriage Return to mark end of line, but since 2001 has supported only Line Feed as end of line.)
When I say "streams of bytes", I mean that there is no meta-data saying how long a line is or where the line is to be found in the file. The only supported way to find a particular line number on a text file is to start at the beginning of a file and read the file, counting delimiters as you go, until you have read in as many previous lines as you need.
Because of this, if you need to change the length of a line in a text file (for example 10.001 changing to 9.999 uses one fewer characters), then you only have two choices:
- Create a new file that has the updated information; OR
- Find the position you want to make the update, and change the complete rest of the file, possibly truncating the file if it became shorter.
However... MATLAB does not support file truncation, so if your text file is going to become shorter, then the **only* supported operation is to write a new file with the updated information (in practice you could also call into system libraries to truncate the file for you, but those system libraries are operating-system specific...)
So, NO, you cannot just update a csv file "in place" -- not unless the size of the text stays exactly the same.
This differs from Excel .xls files: those are binary files and for numeric fields it is possible to update an existing number "in place".
Excel .xlsx files are actually a zip'd directory containing several .xml text files, with all numbers being stored as text, not as binary.
It is possible to use writetable() to ask that a particular cell of a .xls or .xlsx file be updated; this just has the effect of calling functions that do the complicated updating work for you. But it doesn't work (reliably) for .csv files.
Thus... using writetable() to write out the complete .csv file each time is your easiest and most reliable update method.
By the way: I suspect that your assignment does not ask you to update the .csv file each time. It might ask that the csv file is updated with all of the transactions, but the wording probably allows for the possibility of doing the updates to the file after all of the transactions are completed.
Tariq Hammoudeh
on 4 Dec 2021
thank you so much for that.
What i need to do is after a transaction (withdrawal or deposit) i need to credit or debit the amount to the balance. And i need to always have the csv file up to date with correct balances.
So is writing a new table then exporting it as a new file my only option?
Walter Roberson
on 5 Dec 2021
You readable() the csv file into a table() object. You might extract some information from the table such as the list of accounts to make processing easier. As you go through the transactions you will use the stored information to validate the transaction, and you will update the information into the table object. To write the table object back to csv file you writetable() it. There is no need to create a "new" table() object as you proceed, just update the existing one.
Walter Roberson
on 5 Dec 2021
"So is writing a new table then exporting it as a new file my only option?"
No. You can use separate variables instead of a table object. Then you can fopen a new file and use fprintf() to write values to the file. After you fclose(), movefile() the new file to the old name.
Writing directly to the old file is not recommended: if something goes wrong then you no longer have a valid file.
Updating the file "in place" is a technical challenge that I do not recommend.
Tariq Hammoudeh
on 5 Dec 2021
Ok so updating the table i get with
"Data=readtable('NaiveBankData.csv');"
is possible right? If it is, ill work on that then confirm if i need to update the actual csv file or not.
Walter Roberson
on 5 Dec 2021
filename = 'https://www.mathworks.com/matlabcentral/answers/uploaded_files/821745/NaiveBankData.csv';
Data = readtable(filename)
Warning: Column headers from the file were modified to make them valid MATLAB identifiers before creating variable names for the table. The original column headers are saved in the VariableDescriptions property.
Set 'VariableNamingRule' to 'preserve' to use the original column headers as table variable names.
Set 'VariableNamingRule' to 'preserve' to use the original column headers as table variable names.
Data = 5×2 table
AccountNumber Balance
_____________ _____________
105 {'£6,327.15'}
234 {'£203.54' }
576 {'£52.45' }
594 {'£5,489.00'}
876 {'£1,245.80'}
balance = cellfun(@(x) x(all(x~=('£,')',1)),Data.Balance,'uniform',false);
balance = str2double(balance);
Data.Balance = balance
Data = 5×2 table
AccountNumber Balance
_____________ _______
105 6327.1
234 203.54
576 52.45
594 5489
876 1245.8
Data.Balance(4)
ans = 5489
Data.Balance(4) = Data.Balance(4) - 100;
Data.Balance(4)
ans = 5389
Data
Data = 5×2 table
AccountNumber Balance
_____________ _______
105 6327.1
234 203.54
576 52.45
594 5389
876 1245.8
This appears to me to have updated the table() object.
This code does not update the file on disk. For the file on disk, you have to decide whether it is okay to emit the balance as pure numbers, or if you need to format it back to include commas and currency symbols.
Tariq Hammoudeh
on 6 Dec 2021
Ok I have everything but because i cant choose which account balance to change, i need it to change the balance of the inputted account. so i tried:
Data.Balance(ac)= Data.Balance(ac)-withdrawAmount;
And after a withdraw it does change the correct balance, but then when i run it again, the balance in the table() resets. so is there a way to make that change to the table() permenant.
Walter Roberson
on 6 Dec 2021
When you run the code again you are re-reading the file, but you did not save the table to the file. The way to save to the file depends on whether you need to reinsert the £ and commas.
Tariq Hammoudeh
on 6 Dec 2021
oh i get it now, but where would i be able to find information on how to save the updated table to the existing file, because im trying to learn it either way. Like i want to learn how to write the new table to the existing file and how to put the commas and pound sign back, whether i need it for this assignment or not.
Tariq Hammoudeh
on 7 Dec 2021
Ok so i tried
Data.Balance(ac)= Data.Balance(ac)-(withdrawAmount + 1.5);
writetable(Data, 'NaiveBankData.csv');
and this does update the csv file but it removes the pound sign and the commas, from the table in the file, so when i run it again i get this error:
Error using cellfun
Input #2 expected to be a cell array, was double instead.
Error in Matlab (line 20)
balance = cellfun(@(x) x(all(x~=('£,')',1)),Data.Balance,'uniform',false);
So i do have to put in the pound sign and commas or else it doesnt work the second time.
Tariq Hammoudeh
on 7 Dec 2021
But if there is a way to write the new table into the file without putting the comma and pound sign back in, thats also fine, its just that i cant find it in the documentaion.
DGM
on 7 Dec 2021
Edited: DGM
on 7 Dec 2021
You should be able to do that conditionally
% convert balance to numeric data
if iscellstr(Data.Balance)
balance = cellfun(@(x) x(all(x~=('£,')',1)),Data.Balance,'uniform',false);
Data.Balance = str2double(balance);
end
Then you should be able to use the code on the file that writetable() produces.
Tariq Hammoudeh
on 10 Dec 2021
Ok so this works perfectly, but for some reason when i click on the table object named Data in the workspace the balance numbers are formatted like this: 3.08597e+03 even though this number would show up like
this: 3339.65 in the csv file. and if i type Data in the command line, the table shows with rounded values of balances. so 3339.65 would show up in the command line as 3339.7.
Is there a way to fix this without changing alot, because everything works the way it should and its not a big issue.
Walter Roberson
on 10 Dec 2021
In the main command window, use Preferences -> Command Window -> Text Display -> Numeric format and select "Long g". Also Preferences -> Variables -> Format -> default array format and select "Long g"
You might have to close the variable browser and re-open it.
More Answers (0)
See Also
Categories
Find more on Spreadsheets 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!An Error Occurred
Unable to complete the action because of changes made to the page. Reload the page to see its updated state.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom(English)
Asia Pacific
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 日本Japanese (日本語)
- 한국Korean (한국어)