array of numbers and strings

조회 수: 3 (최근 30일)
Marc-Olivier Labrecque-Goulet
Marc-Olivier Labrecque-Goulet 2017년 3월 4일
Hi, I have an issue creating string. let say I have 2 numbers and a string:
nb1 = 12;
nb2 = 1;
str1 = '+';
I want to create a variable (array or a string) from these 3 variables:
op = {nb1 str1 nb2} ;
op is an operation, (i will later need to acces nb2 as a number value and fprint the whole op.)
I then need to make an array of op. This array is storing every operations made.
history = [];
for i = 1 : 5
history = [history op]; %adding the last operation in the history
nb1 = nb1 + i; %just changing the numbers in a random way to illustrate
nb2 = nb2 - i;
str1 will also change for an other string, I lack imagination to illustrate that...
op = {nb1 str1 nb2};
end
i want to be able to access a certain operation in the history and fprintf it on the screen.
op = history (n*2);
fprintf ('%s',op);
And finally, also change the value of a number from the previous value.
nb1 = op{1};
op and nb1 at this stage should be what they were "n" operation before.

채택된 답변

Geoff Hayes
Geoff Hayes 2017년 3월 4일
Marc-Olivier - the line of code
op = {nb1 str1 nb2} ;
will create a 1x3 cell array of two numbers (in the first and third positions) and a string (for the operation). It is not a string.
If you have several operations/equations, then you can concatenate them together to form the history as
history = [];
for k=1:5
numA = randi(255,1,1);
numB = randi(255,1,1);
operator = '+';
eqn = {numA operator numB};
history = [history ; eqn]; % vertical concatenation using ;
end
If you wish to access the third equation in the history, you would then do
thirdEquation = history(3,:);
You are accessing the third row (so use 3) and you want all of the columns (so use the colon).
To print this equation, you would do
fprintf('%d %s %d\n', thirdEquation{1}, thirdEquation{2}, thirdEquation{3});
where you specify the type of each element in your equation: number, string, number.
You should then be able to manipulate any of the values in this third equation via the usual manner of accessing elements in the cell array.
  댓글 수: 2
Marc-Olivier Labrecque-Goulet
Marc-Olivier Labrecque-Goulet 2017년 3월 4일
thanks a lot Geoff, im going to try this right away.
Marc-Olivier Labrecque-Goulet
Marc-Olivier Labrecque-Goulet 2017년 3월 4일
update : everything work fine, ive finally finish the function Undo of my "very basic" calculator Ty very much

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by