Using Set() to change data in a figure to a matrix

I'm trying to the set function to change the x and y data in a figure to a pair of figures using the following code
a = [1 3; 4 2]; b = [1 2; -5 -2];
graph = plot(a, b);
set(graph, {'xdata'}, b, {'ydata'}, a)
but it gives the error,
Error using matlab.graphics.chart.primitive.Line/set
Invalid parameter/value pair arguments.
when it reaches the third line.
I understand that making the variables 'a' and 'b' linear vectors would remove the error, but I specifically want these lines to plotted seperately.

 Accepted Answer

Jan
Jan on 23 Mar 2021
Edited: Jan on 23 Mar 2021
a = [1 3; 4 2]; b = [1 2; -5 -2];
graph = plot(a, b);
pause(1) % Only to see the changes
set(graph, {'xdata'}, mat2cell(b, [1,1], 2), ...
{'ydata'}, mat2cell(a, [1,1], 2))
If you provide several graphic objects, the name of the property and the data must be cell arrays.

6 Comments

Thanks you so much! This works perfectly for what I need and your response was incredibly quick!
This is a little embrassing but I don't understand mat2cell well enough to upscale this code e.g.
a = [1 3 4; 4 2 6]; b = [1 2 0; -5 -2 -4];
Or larger arrays for 'a' and 'b'.
The general method to split the rows of b into a cell array:
mat2cell(b, ones(1, size(b, 1)), size(b, 2))
I find mat2cell not intuitive also. You can write your own function to do this:
function C = Rows2Cell(M)
s1 = size(M, 1);
C = cell(s1, 1);
for k = 1:s1
C{k} = M(k, :);
end
end
So would it look like this? @Jan
a = [1 3 4; 4 2 6]; b = [1 2 0; -5 -2 -4];
graph = plot(a, b);
pause(1) % Only to see the changes
set(graph, {'xdata'}, mat2cell(b, ones(1, size(b, 1)), size(b, 2)), ...
{'ydata'}, mat2cell(a, ones(1, size(a, 1)), size(a, 2)))
But I don't think this works, it gives the error
Error using matlab.graphics.chart.primitive.Line/set
Value cell array handle dimension must match handle vector length.
What do you think? If graph = plot(a,b) produces 3 lines, the columns of the inpzuts are used. My idea, that the rows are used was obviously wrong. Then it is time for reading the documentation and some tests. My result looks ugly:
set(graph, {'xdata'}, mat2cell(b, size(b, 1), ones(1, size(b, 2))).', ...
{'ydata'}, mat2cell(a, size(a, 1), ones(1, size(a, 2))).');
Perhaps this is nicer:
set(graph, {'xdata'}, Cols2Cell(b), ...
{'ydata'}, Cols2Cell(a));
function C = Cols2Cell(M)
[~, s2] = size(M);
C = cell(s2, 1);
for k = 1:s2
C{k} = M(:, k);
end
end
Yup that works like a charm and I think I understand how setting cells works a lot better now. Seems like another mistake I made was trying to use set() to change the number of parameters in the plot e.g. trying to set a 2x5 onto what was originally a 2x3 or a 2x6 data set.

Sign in to comment.

More Answers (0)

Categories

Products

Release

R2020b

Asked:

on 23 Mar 2021

Commented:

on 24 Mar 2021

Community Treasure Hunt

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

Start Hunting!