开发者

Adding text or string to the row of a matrix

I am having issues adding a label to the rows of a matrix. Here is the code I currently have:

Probability = ['Hole 1', US_par3_Win, par3_Draw, EU_par3_Win;
               'Hole 2', US_par3_Win, par3_Draw, EU_par3_Win]

I added the labels with single quotes, but am getting an error. Could anyone开发者_如何转开发 guide me in the right direction? Thanks!


MATLAB matrices can only store elements of the same type. Cell arrays on the other hand don't have this restriction. I suggest you keep the matrix as it is, and add another cell array variable to store the label of each row. Example:

M = [1 2 3; 4 1 2; 4 1 1];
labels = {'row1'; 'row10'; 'row100'};

%# display 2nd row and its label
M(2,:)
labels{2}


If the variables, such as US_par3_Win, are scalars, the following should work:

Probability = {'Hole 1', US_par3_Win, par3_Draw, EU_par3_Win;...
               'Hole 2', US_par3_Win, par3_Draw, EU_par3_Win}

However, if the variables are e.g. 18-by-1 arrays, then you should combine them by creating first an array of Hole names

holeNames = arrayfun(@(x)sprintf('Hole %i',x),(1:18)','UniformOutput',false);  %'#

And then catenate like this

Probability = [holeNames,num2cell(US_par3_Win),...
               num2cell(par3_Draw),num2cell(EU_par3_Win)];

However, you're most likely much better off if instead of writing 'Hole 1', 'Hole 2' etc, you just put the number of the hole in the first column of your probability array, i.e.

Probability = [1, US_par3_Win, par3_Draw, EU_par3_Win;...
               2, US_par3_Win, par3_Draw, EU_par3_Win]


Another approach to organize your data might be a struct. If you want to go even further use classes to model your data.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜