Logical indexing of cell array in MATLAB - matlab

I want to do
myCellArray = myCcellArray{indices}
where indices is just 0s and 1s, with same number of elements as the number of rows in myCellArray, but it doesn't work. What should I do?

You need to use parenthesis instead of curly braces to do the indexing.
>> arr = cell(2,2);
>> arr{1,1} = magic(4);
>> arr{1,2} = 'Hello';
>> arr{2,1} = 42;
>> arr{2,2} = pi;
>> arr
arr =
[4x4 double] 'Hello'
[ 42] [3.1416]
>> idx = logical(zeros(2,2));
>> idx(1,1) = true;
>> idx(2,2) = true;
>> arr(idx)
ans =
[4x4 double]
[ 3.1416]

If you want to slice a cell-array, use parentheses. Example:
%# random cellarray of strings, and a logical indices vector
myCcellArray = cellstr(num2str((1:10)','value %02d')); %'
indices = rand(size(myCcellArray)) > 0.5;
%# slicing
myCellArray = myCcellArray(indices)

What amro said is right, you should use parentheses.
But another critical thing is to use booleans not numeric 1 and 0 here.
so if you have numbers
I = [0 0 0 1 0 1]
you should use
myCellArray(I~=0)
to index it. Confusingly, a boolean array is displayed as ones and zeros in Matlab, although it is represented quite differently internally.

Related

Repeat letters within a string in Matlab

I would like to generate a string in Matlab that looks like
"BBBBBBBBBBBBBBBBCCCCCCCCCCCCCC"
where "B" is repeated m times and "C" is repeated n times. Is there any function with inputs similar to ("B","C",n,m) doing this?
You can use the function repelem to repeat the characters the wanted number of times.
str = 'BC' %This is character vector, NOT a string
n = 4; m = 3;
res = repelem(str,[n,m])
res =
'BBBBCCC'
repmat function works on char arrays, and concatenation operators too.
So:
copyfcn = #(B,C,n,m) [repmat(B,[1 n]) repmat(C,[1,m])];
copyfcn('B','C',8,4)
ans =
'BBBBBBBCCCC'
If you want the output to be a string rather than a char array, you can just wrap it in the string() function.
copyfcn2 = #(B,C,n,m) string([repmat(B,[1 n]) repmat(C,[1,m])]);
copyfcn2('B','C',8,4)
ans =
"BBBBBBBBCCCC"
You can make your own function using repmat:
>> f = #(a,b,n,m) [repmat(a, [1 m]) repmat(b, [1 m])];
>> f('B','C',12,14)
ans =
'BBBBBBBBBBBBBBCCCCCCCCCCCCCC'

How to combine two matrices column wise to strings separated by comma?

I have two matrices
A = [ 1 3
4 3]
B = [ 2 1
4 1 ]
I want to combine A and B to produce the string array
C = [ "1,2" "3,1"
"4,1" "3,1" ]
How can I do this in MATLAB? I tried it this way
for i = 1: 4;
for j = 1: 4;
fprintf('%0.2f,%0.2f\n',A(i,j),B(i,j) )
end
end
Appreciate your suggestions !
A = [1 3; 4 3];
B = [2 1; 4 1];
C = A + "," + B
C =
% 2×2 string array
% "1,2" "3,1"
% "4,4" "3,1"
The first thing to note, is that there is a difference between strings "string" and character arrays 'character array'. Whereas strings are one entity, the character array is an array of characters.
Thus you can make the following assignment
A(1) = "Hello";
but not
B(1) = 'Hello';
because the B(1) is one value, and 'Hello' is 5 values (H,e,l,l,o).
Secondly, you cannot use fprintf as you suggest in the comments as it only prints (as in its name) and the variable returned by fprintf is the number of characters printed. Instead, to construct the string use strcat together with num2str, such that you get:
A = rand(2); %some matrices
B = rand(2);
for i = 1:2
for j = 1:2
C(i,j) = strcat(num2str(A(i,j)),",",num2str(B(i,j)));
end
end
EDIT: If you are anyway going to interchange the comma for \pm in LaTeX, you can just do it when constructing C by using
C(i,j) = strcat(num2str(A(i,j)),"\pm",num2str(B(i,j)))
instead.

Push array onto 2D array (matrix) in MATLAB

For God only knows what reason, we're being asked to use MATLAB in an AI course. All I want to do is initialize an array, and push arrays onto it. In Ruby, this would be:
multi_arr = []
an_arr = [1, 2, 3, 4]
multi_arr << an_arr
Done! Unfortunately I can't find a similarly simple solution in MATLAB.
Any advice would be extremely appreciated.
EDIT: for the interested, here's the rather ungraceful solution I arrived at:
child_states = []
child_state = [0,1,2,3,4,5,6,7,8]
% returns [rows, columns]
dimensions = size(child_states)
child_states(dimensions(1)+1, 1:9) = child_state
You can append array to an array in matlab without knowing the dimensions but it won't be very efficient because matlab will allocate space for the whole array each time you do it. Here's how to do it:
arrays = [];
arr1 = [1,2];
arr2 = [3,4,5];
% append first array
arrays = [arrays ,arr1 ]
% append second array
arrays = [arrays ,arr2 ]
arrays =
1 2
arrays =
1 2 3 4 5
if each of the arrays you want to append have the same length, then you can append them as rows:
arrays = [];
arr1 = [1,2,4];
arr2 = [5,6,7];
% append first array
arrays = [arrays ; arr1 ]
% append second array
arrays = [arrays ; arr2 ]
arrays =
1 2 4
arrays =
1 2 4
5 6 7
for more of a ruby like array appending you should use cell arrays:
cells = {};
cells = [cells ,[4,5] ]
cells = [cells ,[1,1,1] ]
cells = [cells ,['hello']]
cells =
[1x2 double] [1x3 double] 'hello'
GIYF. It seems that you are looking for horzcat and vertcat. Check out MATLAB's doc at Creating and concatenating matrices.; from vertcat page:
C = vertcat(A1,...,AN) vertically concatenates arrays A1,...,AN. All arrays in the argument list must have the same number of columns.
If the inputs are multidimensional arrays, vertcat concatenates N-dimensional arrays along the first dimension. The remaining dimensions must match.
Here's a function that's supposed to do what you want: concatenate a row vector to an array regardless of size. This function will check the dimension along the second axis of input and output array and pad zero to whichever one that is smaller so they can be concatenated along the first axis.
function m = freevertcat(m, n)
if isempty(m)
m = cat(1, m, n);
else
size_m = size(m, 2);
size_n = size(n, 2);
if size_m > size_n
n(size_n+1 : size_n + size_m - size_n) = 0
elseif size_n > size_m
m(:, size_m+1 : size_m + size_n - size_m) = 0;
end
m = cat(1, m, n);
end
example usage
m = []
n = [1,2,3,4,5]
m = freevertcat(m,n)
p = [3,3,3]
m = freevertcat(m,p)
You'll get
m = 1 2 3 4 5
3 3 3 0 0

Vectorized or single line evaluation of function array in MATLAB

In a previous question, a user asked about iterating over a cell array of anonymous functions. I am wondering whether there is a way to evaluate a set of functions without the explicit use of a for loop.
As an example, the following code creates an array of (simple) functions, evaluates them for a fixed value and stores the results:
fcnList = {#(x) (x+1), #(x) (x+2)};
a = 2;
for i = 1:numel(fcnList)
y(i) = fcnList{i}(a);
end
Is there a way to do this without looping?
For your example, you could do the following using the cellfun function:
fcnList = {#(x) (x+1), #(x) (x+2)};
a = 2;
cellfun(#(func) func(a),fcnList)
ans =
3 4
Where I have created a handle called func which accepts as input a function from the fcnList variable. Each function is then evaluated for a.
If you need to pass a vector instead of a scalar, for instance b, you will need to set the 'UniformOutput' option to false:
b=[3 4]
fcnList = {#(x) (x+1), #(x) (x+2)};
cellfun(#(func) func(b),fcnList,'UniformOutput',false)
ans =
{
[1,1] =
4 5
[1,2] =
5 6
}
To avoid a for loop or cellfun (which is more or less the same as a loop), you can define a single function with vector output:
fcn = #(x) [x+1, x+2];
Then fcn(a) gives you a vector cointaining the results:
>> fcn = #(x) [x+1, x+2];
>> a = 2;
>> fcn(a)
ans =
3 4
If the results of each original function have different sizes you can define a single function with cell array output:
>> fcn = #(x) {x+1, [x+2; x+3]};
>> a = 2;
>> x = fcn(a)
x =
[3] [2x1 double]
>> celldisp(x)
x{1} =
3
x{2} =
4
5

Check for [] simulink

However I try to test if x is [] I fail, seems that it should be trivial, but can't figure out how to do it.
if I run x = rmi('get',subsystemPath);
ans = []
I've tried
x == []
x
isempty(fieldnames(x))
isEmpty(x)
but nothing works
function requirements = GetRequirementsFromSubsystem(subsystemPath)
x = rmi('get',subsystemPath);
if(isempty(fieldnames(x))) %%%%%%%%%%%%%%%%<------
requirements = 0;
else
requirements = {x.description}; % Fails if do this without a check
end
end
Any ideas?
x is a struct, right? In that case, according to this posting on the MATLAB newsgroup, there are two kinds of emptiness for structs:
S = struct() => no fields
isempty(S) is FALSE, because S is a [1 x 1] struct without fields
S = struct('Field1', {}) => fields, but no data
isempty(S) is TRUE, because S is a [0 x 0] struct with fields
For me, isempty(fieldnames(S)) works only for the first case in Octave, at least.
If x on the other hand, is an array, not a struct, then isempty(x) should work.
>> S = struct()
S =
scalar structure containing the fields:
>> isempty(S)
ans = 0
>> isempty(fieldnames(S))
ans = 1
>> S = struct('Field1',{})
S =
0x0 struct array containing the fields:
Field1
>> isempty(S)
ans = 1
>> isempty(fieldnames(S))
ans = 0
>> x = []
x = [](0x0)
>> isempty(x)
ans = 1