Looping num2str

26 visualizzazioni (ultimi 30 giorni)
Mohammed Raslan
Mohammed Raslan il 26 Lug 2021
Risposto: Steven Lord il 26 Lug 2021
Hi,
Assuming y = [1,2,3,4]
If I want to add a percentage to each value, I attempt to do for loop as such:
for i = 1:4
x(i) = [num2str(y(i)),'%']
end
But it doesn't work. However if I avoid the for loop and simply do:
x1 = [num2str(y(1)),'%']
x2 = [num2str(y(2)),'%']
...
..
.
x = {x1,x2,x3,x4,x5}
It works just fine. What is the problem in the for loop?
Thanks

Risposte (2)

Steven Lord
Steven Lord il 26 Lug 2021
An easier way to do this is to use a string array.
y = 1:4;
x = y + " %"
x = 1×4 string array
"1 %" "2 %" "3 %" "4 %"

James Tursa
James Tursa il 26 Lug 2021
Modificato: James Tursa il 26 Lug 2021
x(i) references a single element of x. However, the expression [num2str(y(i)),'%'] generates multiple characters. In essence, you are trying to assign multiple characters to a single element, and they just don't fit. Of course, you can use cell arrays for this as you have discovered, since cell array elements can contain entire variables regardless of size or class. Using cell arrays also works in case some strings are longer than others.
Note, you could have just used the curly braces in your for loop to generate the cell array result:
for i = 1:4
x{i} = [num2str(y(i)),'%'];
end
Or generated the cell array result directly with arrayfun:
x = arrayfun(@(a)[num2str(a),'%'],y,'uni',false);

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by