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

4 views (last 30 days)
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
Jan
Jan on 23 Mar 2021
Edited: Jan on 23 Mar 2021
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
Tanson Wang
Tanson Wang on 24 Mar 2021
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

Find more on Creating, Deleting, and Querying Graphics Objects in Help Center and File Exchange

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!