MATLAB: Accessing the index of a matrix element inside the cell array

index of a matrix in cell arrayMATLAB

Hey all,
I have a small question in regarding the access of index of a matrix element inside the cell array.
A = {[1 2 3 4] [ 'Node1' 'Node2' 'Node3']};
Above is my cell array. Now I need to get the index of an element of matrix inside the cell array.
For an example if c = 3, just an example, c may be any number.
then I need it's index like A{1,1}(1,3)
Can anyone help me in this?
Thanks in advance

Best Answer

First, a few recommendations.
  • If you're using vectors use linear indexing instead of 2D indexing. I.e. X{1} instead of X{1, 1}.
  • if n<=3 ... elseif n>3 ... end, if the if is false you're guaranteed that the elseif is true. Therefore the elseif is not needed, you can simply write if n<=3 ... else ... end. In general, you should always finish by an else, not an elseif.
  • don't use the same variable name, particularly one as meaningless as c for storing to different things. In your code, c is used to store the index where plotnumber is found in the cell array, then to store plotnumber.
  • Whenever you end writing the same lines of code with only small variations between them it's a clear indication that there must be a better way, such as indexing.
In particular, with that last point, we can rewrite your code as:
[f,T1, X] = Samplemodel_Instat('Measuring_Data.mat');
% X will be like this X = {[ 2 4] [ 'Oil' 'Air']};
%Now defines the constants that will be used for plots, as 5xN matrices (as there are 5 different possible plots)
Colours = [0.831372559070587 0.815686285495758 0.7843137383461;
0.25 0.25 0.25;
0.952941179275513 0.87058824300766 0.733333349227905;
0.31 0.31 0.31;
0.831372559070587 0.815686285495758 0.7843137383461];
LineWidths = [0.5; 4; 2; 2; 0.5]; %0.5 is default for plot
LineStyles = {'-'; '-.'; '-'; '-'; '-'}; %'-' is default for plot
Markers = {'none'; 'none'; 's'; 'none'; 'none'}; %'none' is default for plit
for plotnumber = 1:n
whichmodel = find(X{1} == plotnumber,1);
if ~isempty(whichmodel)
if n <= 3
plotstyle = 1; %which row of Colours, LineWidths, etc.. to use
else
plotstyle = discretize(plotnumber, ceil((0:4)*n/4), 'IncludeEdge', 'right') + 1;
end
if ismember(plotstyle, [1 3])
plotindices = (1:150:numel(f)) / 3600;
else
plotindices = (1:200:numel(f)) / 3600;
end
plot(f(indices), T1(plotnumber, indices), ...
'Color', Colours(plotstyle, :), ...
'LineWidth', LineWidths(plotstyle), ...
'LineStyle', LineStyle{plotstyle}, ...
'Marker', Markers{plotstule}, ...
'MarkerFaceColor', [1 1 1]);
legend(X{2}(whichmodel)); %index 2nd element of cell array
end
end