Effacer les filtres
Effacer les filtres

How can I add a different string to each element in a matrix?

1 vue (au cours des 30 derniers jours)
Asher Zaidi
Asher Zaidi le 7 Juin 2018
Commenté : Ameer Hamza le 8 Juin 2018
I have a (soon to be) large vector and I want to add a string before each element, something like:
"Data Trial 1 - (1st vector element)"
"Data Trial 2 - (2nd vector element)"
... and so on
This is my code:
files = dir('*.xlsx');
for i=1:length(files)
x = importdata(files(i).name); % Creates x.data and x.textdata
z1 = x.data(:,5); % Grabs column 5 from x.data
z2 = x.data(:,6); % Grabs column 6 from x.data
%%Obtains value closest to 0 in column 'z2' (column 6)
numb=0;
[~, imin] = min(abs(z2 - numb));
plot(z1,z2);
hold on
plot(z1(imin),z2(imin),'*')
value(i) = z2(imin);
end
%%Displays value closest to 0 in the respective order the data was imported
disp(value')
After the code is run, the vector looks like this:
>> test2
0.0225
0.0269
0.0258
0.0284
0.0246
0.0231
0.0249
0.0271
0.0341
0.0338
How can I add a string before each number in the vector?
  1 commentaire
Paolo
Paolo le 7 Juin 2018
Please provide an example of desired output. Do you want to concatenate a string with the number?

Connectez-vous pour commenter.

Réponse acceptée

Ameer Hamza
Ameer Hamza le 7 Juin 2018
One approach is as follow if you want to store all the values in an array,
values = [1,2,3,4,5];
charValues = compose('Data Trial %d - %f', (1:length(values))', values')
charValues =
5×1 cell array
{'Data Trial 1 - 1.000000'}
{'Data Trial 2 - 2.000000'}
{'Data Trial 3 - 3.000000'}
{'Data Trial 4 - 4.000000'}
{'Data Trial 5 - 5.000000'}
If you just want to display, then try
disp(sprintf('Data Trial %d - %f\n', (1:length(values))', values'))
  2 commentaires
Asher Zaidi
Asher Zaidi le 8 Juin 2018
Exactly what I was looking for, thank you!
Ameer Hamza
Ameer Hamza le 8 Juin 2018
You are welcome.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Produits


Version

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by