I would like to create an array to store a password, website combo.

조회 수: 5 (최근 30일)
Luke
Luke 2023년 11월 13일
답변: Chunru 2023년 11월 14일
I would like to write a function to enter strings of passwords and websites with each new entrie going to the next line of the array. However I am finding that the script I have now is overwriting the previous entries.
function passwordArray = addPasswordWithWebsite(passwordArray, password, website)
% Check if the passwordArray variable exists
% Add the website and password pair to the array
passwordArray{1, end+1} = website;
passwordArray{2, end+1} = password;
end
This is the code I have thus far. Also do I have to index the array in the main script each time, as when I try to run it after closing Matlab it says passwordArray variable is undefined.
  댓글 수: 1
Voss
Voss 2023년 11월 13일
Notice that the code as shown adds two columns to passwordArray:
website = 'google.com';
password = 'PasSwOrD';
% let's say initially passwordArray has 0 columns:
passwordArray = cell(2,0);
% this adds a new column:
passwordArray{1, end+1} = website;
% and this adds another new column:
passwordArray{2, end+1} = password;
% so now there are two columns, one with the website and one with the
% corresponding password:
passwordArray
passwordArray = 2×2 cell array
{'google.com'} {0×0 double} {0×0 double } {'PasSwOrD'}
You can change the second end+1 to end:
% let's say initially passwordArray has 0 columns:
passwordArray = cell(2,0);
% this adds a new column containing the website:
passwordArray{1, end+1} = website;
% and this fills in the 2nd row in the last column with the password:
passwordArray{2, end} = password;
% so now there is one column:
passwordArray
passwordArray = 2×1 cell array
{'google.com'} {'PasSwOrD' }
Or add both the website and the password to the array at the same time:
% let's say initially passwordArray has 0 columns:
passwordArray = cell(2,0);
% this adds a new column containing both website and password:
passwordArray(:, end+1) = {website; password};
% so now there is one column:
passwordArray
passwordArray = 2×1 cell array
{'google.com'} {'PasSwOrD' }

댓글을 달려면 로그인하십시오.

답변 (1개)

Chunru
Chunru 2023년 11월 14일
Use string array instead of cell array for efficiency. You can also considre to use table.
pa = ["abc", "def"]
pa = 1×2 string array
"abc" "def"
pa = addPasswordWithWebsite(pa, "123", "456")
pa = 2×2 string array
"abc" "def" "123" "456"
function passwordArray = addPasswordWithWebsite(passwordArray, website, password)
% Check if the passwordArray variable exists
% Add the website and password pair to the array
passwordArray(end+1, :) = [website, password];
end

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

제품


릴리스

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by