Can i pass an array of n strings to a function that takes n strings as input?

4 views (last 30 days)
I am plotting N functions on a 2D graph, and i would like to make a legend for each function before knowing how many functions i will have. I thought of creating an array of names in the same loop as described in the code below, but even though the function legend() accepts n character vectors, it wont accept an array containing those as a parameter. Is there any way to perform this?
[~,n]=size(X)
nameArray=[1,n]
hold on
for i=1:n
plot(X( : ,n),Y( : ,n));
nameArray(i)= [ 'function number: ' num2str(i)]
end
legend(nameArray)
hold off

Answers (2)

Jan
Jan on 29 Oct 2022
Edited: Jan on 29 Oct 2022
nameArray=[1,n]
This creates an [1 x 2] vector. The 1st element is 1, the second is n.
Inside the loop you do not work with strings, but with CHAR vectors. Then you need a "cell string" (which has no relation to "strings", so the name is misleading...):
nameArray = cell(1,n);
...
nameArray{i} = [ 'function number: ' num2str(i)];
Alternative with modern strings:
n = size(X, 2);
nameArray = strings(1, n);
hold on
for i = 1:n
plot(X(:, n),Y(:, n));
nameArray(i) = ["function number: " + i];
end
legend(nameArray)

Star Strider
Star Strider on 29 Oct 2022
The plot calls should probably be referencing ‘i’ instead of ‘n’ and if you have R2016b or later, you can use string arrays —
X = randn(5);
Y = randn(5);
[~,n]=size(X)
n = 5
nameArray=[1,n]
nameArray = 1×2
1 5
figure
hold on
for i=1:n
nameArray = "function number: " + num2str(i);
plot(X( : ,i),Y( : ,i), 'DisplayName',nameArray);
end
hold off
legend('Location','best')
.

Community Treasure Hunt

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

Start Hunting!