Add value to cell in a loop - matlab

I have simple code as below and try to insert the values into cell array.
a = cell(14,1);
for i = 1:14
a(i:1)=sin(i)
end
However error came out as:
Conversion to cell from double is not possible.
What is the problem for this code?

Either expand the cell, or wrap the result of the sin function in a cell.
a = cell(14,1);
b = cell(14,1);
for ii = 1:14
a{ii} = sin(ii);
b(ii) = {sin(ii)};
end
isequal(a,b)
ans =
logical
1

Your Syntax is wrong. a(i:1) can not work inside a loop over i. Simply using a(i) will give you the desired result.

Related

How to take transpose of N-D array in matlab?

I am using the following code to get all the possible combinations of the rows of a matrix.
function rComb(matrix)
rows = size(matrix,1)
for n = 1:rows
rowsCell = num2cell(matrix,2);
r = nchoosek(1:size(matrix,1),n);
out = cell2mat(reshape(rowsCell(r.',:).',n,1,[]))
end
end
Now I want to take the transpose of the out variable, and I am using this code.
function rComb(matrix)
rows = size(matrix,1)
for n = 1:rows
rowsCell = num2cell(matrix,2);
r = nchoosek(1:size(matrix,1),n);
out = cell2mat(reshape(rowsCell(r.',:).',n,1,[]))
transp = out'
end
end
And I am facing this error...!!
"Error using '
Transpose on ND array is not defined. Use PERMUTE
instead."
Can you solve this issue?
One more thing can a function give us multiple outputs like all the possible combinations of output? Like in the above code if I place ';' after out variable statement this function won't display anything :/.

How to access function handles in a cell array?

rate_arr_cst_1 = #(t) 2*sin(t)+10;
rate_arr_cst_2 = #(t) 3*sin(2*t)+8;
rate_arr_cst_h = {rate_arr_cst_1, rate_arr_cst_2};
I defined a cell array in such way and try to access in the following way:
i=1;
h = rate_arr_cst_h(i);
but what I get here is still a cell array, meaning i can't use h to evaluate t=0.1.
Your help is much appreciated!
When you do h = rate_arr_cst_h(i);, you are accessing the i^th element of the cell array, which is still a cell. If you want to access the contents of i^th cell in the cell array, you need to do: h = rate_arr_cst_h{i};. Note the use of curly brackets.
Either use a for loop:
for ii = 1:numel(rate_arr_cst_h)
hh(ii) = rate_arr_cst_h{ii}(i);
end
or you can use cellfun:
hh = cellfun(#(f) f(i), rate_arr_cst_h);

A different statement for each for-loop iteration

I want to print a different statement for each iteration of a for-loop. I have tried assigning each statement to a variable, putting each variable in a vector and calling a different index of the vector for each iteration like this:
A = 1st statement
B = 2nd statement
C = 3rd statement
v = [A,B,C]
for i = 1:3
fprintf('%s',v(i))
end
but it only prints the first statement one letter per iteration. What would be a better way to do this?
In a 1xn array, n alphabets will be stored. That is why you see first three letters getting printed (i=1:3). Assuming all the statements do not have the same length, you could save A,B,C in a cell array. Then access it as usual.
v={A;B;C};
for i = 1:size(v,1) %always try to use size(v,1) instead of hard-coding.
fprintf('%s',v{i,1})
end
If all statements have the same length, then you have them in a matrix.
v=[A;B;C];
for i = 1:size(v,1) %always try to use size(v,1) instead of hard-coding.
fprintf('%s',v(i,:))
end
You can use the following ...
A = '1st statement'
B = '2nd statement'
C = '3rd statement'
v = {A;B;C}
for i = 1:3
fprintf('%s ',v{i,1}))
end
Note the use of {;;;} (cell array ... http://uk.mathworks.com/help/matlab/cell-arrays.html)
rather than [,,,](matrix... http://uk.mathworks.com/help/matlab/learn_matlab/matrices-and-arrays.html).

Create multiple variables of same size in Matlab

Say, I want to create 3 variables of same size in MATLAB:
a = zeros(3,3);
b = zeros(3,3);
c = zeros(3,3);
Is there any fast way to do this, I know this is not working but I think of something like
a,b,c = zeros(3,3);
Any suggestions?
To use deal there is no need to wrap it in a cell as NKN suggested:
[a,b,c]=deal(zeros(3,3))
Although you can do this:
a = zeros(3); % a 3x3 zero matrix
b = a;
c = a;
If you define the values that you want to assign, in a cell, the other way (faster) is:
c={zeros(3)};
[a1,a2,a3,a4]=deal(c{1})
it means that you put your assigning value in a cell and then use deal function. Notice that the a1,a2,a3,a4 does not have cell formats, but double formats and actually this is a very fast method.
If you use cell foramt you can assign more values at the same time, for example:
C = {rand(3) ones(3,1) eye(3) zeros(3,1)};
[a,b,c,d] = deal(C{:})
otherwise you can just get rid of the cell and use:
c=zeros(3);
[a1,a2,a3,a4]=deal(c);
as Daniel Suggested.

First input must be function handle error using arrayfun()

I'm trying to use arrayfun() to map a function over a cell array. The following is happening:
>> arrayfun(solveFunc, equArray)
Error using arrayfun
First input must be a function handle.
Error in solve>genGuess (line 33)
funcVals = abs(arrayfun(inFunc, xValues));
Error in solve (line 8)
x = genGuess(inFunc, varargin{1}, varargin{2});
Error in makeSolveFunc>#(func)solve(func,start,stop) (line 3)
sFunc = #(func) solve(func, start, stop);
But, the first input IS a function handle. Also... if I manually apply the function to each element of the provided cell array, everything works fine:
>> solveFunc(equArray{1})
ans =
4.7335
>> solveFunc(equArray{2})
ans =
4.7356
Does anyone know why this would be happening? I assumed that if I could manually apply the function to each element of my array, and the return type of the function was consistent and one of the allowed types (you can't for example have arrayfun return an array of function handles... I already tried doing that), it should work. Perhaps that is not the only requirement.
Here is some code that generates this error:
solve.m
function solution = solve(inFunc, start, stop)
%SOLVE solve an equation using Newton's Method
x = genGuess(inFunc, start, stop);
for i = 1:100
m = getSlope(inFunc, x);
x = (m*x - inFunc(x))/m;
end
solution = x;
end
function slope = getSlope(inFunc, x)
%SLOPE calculate the slope at a given point
inc = 1e-5;
if x ~= 0
inc = inc * x;
end
slope = (inFunc(x + inc) - inFunc(x - inc))/(2*inc);
end
function guess = genGuess(inFunc, start, stop)
%GENGUESS get an initial guess to the solution
xValues = linspace(start, stop, 101);
funcVals = abs(arrayfun(inFunc, xValues));
[~, minIndex] = min(funcVals);
guess = xValues(minIndex);
end
charEqu.m
function equ = charEqu(a)
%CHAREQU create a KP model characteristic equation with provided p
equ = #(x) x + a;
end
makeSolveFunc.m
function sFunc = makeSolveFunc(start, stop)
%MAKESOLVEFUNC return a function that solves an equation
sFunc = #(func) solve(func, start, stop);
end
test.m
pArray = 1:5;
equArray = cell(1,arrayLen);
for i = 1:5
equArray{i} = charEqu(pArray(i));
end
solveFunc = makeSolveFunc(1.1*pi, 2*pi);
alphaAArray = arrayfun(solveFunc, equArray);
I have narrowed down the error to something in genGuess(). For some reason, in the line funcVals = abs(arrayfun(inFunc, xValues)); the variable inFunc is a 1x1 cell array containing a function handle. I have no idea why that would be the case. I traced this back to the anonymous function call #(func) solve(func, start, stop); in the makeSolveFunc() function. There it is still a 1x1 cell array containing a function handle. I'm not really sure where that cell array is coming from as that function is getting called from arrayfun().
Background information on what I'm trying to do in case someone wants to suggest a better way:
I'm trying to solve equations using Newton's method. I have written a function that can solve an equation given an initial guess range. This function is the solve() function you can see in the first error message. It takes a function, and the guess range and returns a function that I'm calling solveFunc(). solveFunc() takes a function and solves it using the initial guess range previously provided.
Maybe I'm just too used to functional programming and should just use a loop.
If the arguments passed to the function handle are contents of elements of a cell array, you need to use cellfun instead of arrayfun:
cellfun(solveFunc, equArray)
This is equivalent to
for i=1:length(equArray)
out(i) = solveFunc(equArray{i});
end
since solveFunc is already a function handle.
Check where the error comes from. This line causes the error:
funcVals = abs(arrayfun(inFunc, xValues));
The first input argument is a 1x1 cell containing one function handle. This is caused because equArray is a cell, thus use cellfun as Jonas already mentioned:
pArray = 1:5;
equArray = cell(1,arrayLen);
for i = 1:5
equArray{i} = charEqu(pArray(i));
end
solveFunc = makeSolveFunc(1.1*pi, 2*pi);
alphaAArray = cellfun(solveFunc, equArray);