MATLAB: Array of numbers and strings

arrayMATLABstrings

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.

Best Answer

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.