A different statement for each for-loop iteration - matlab

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).

Related

Add value to cell in a loop

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.

Printing multiple disp functions with one for loop

So, I have a series of display functions, ranging from x1 to x7. These all contain both strings and variables like:
x1 = ['The result of the scalar multiplication of V and U: ',num2str(scalar_uv)];
x2 = similar to above but with for example a value on the cross multiplication of the two scalars.
Instead of printing out each one through:
disp(x1);
disp(x2);
disp(x3);
I thought it would be possible to print them all out through a for loop or perhaps a nested for loop but I just can't figure out how to do it. I preferably don't want straight up solutions (I won't say no to them) but rather some hints or tips of possible.
A simple example solution would be to make a cell array and loop through it, or use celldisp() to display it. But if you want to print nicely, i.e. formatted specifically, to the command window you can use the fprintf function and format in line breaks. For example:
for displayValue = {x1, x2, x3, x4}
fprintf('%s\n', displayValue{1});
end
If you want more formatting options, such as precision, or fieldwidth, the formatspec code (%s in the example) has many configurations. You can see them on the fprintf helpdoc. The \n just tells the fprintf function to create a newline when it prints.
Instead of creating seven different variables (x1...x7), just create a cell array to hold all your strings:
x{1} = ['The result of the scalar multiplication of V and U: ',num2str(scalar_uv)];
x{2} = ['Some other statement with a value at the end: ',num2str(somevar)];
Now you can write a loop:
for iX = 1:length(x)
disp(x{iX})
end
Or use cellfun to display them without a for loop:
cellfun(#disp,x)
If you really want to keep them named x1...x7, then you can use an eval statement to get your variable names:
for iX = 1:7
disp(eval(['x' num2str(iX)]));
end

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 :/.

Double for loop, how to set non-continuous index?

If I want to construct a double for loop, but for index k I don't want it to be continuous index but like [1,2,4,7]. I tried to do the following, and it did not work.
for i=1:100
for k=1:2:4:7;
b(i)=i*k;
end
end
Anyone could help me deal with that?
When you want to construct an array, you don't want to necessarily use the colon (:) operator unless you want to create a range of values (like you do when you want i to be all values between 1 and 100), instead you want to use square brackets ([]) with comma separators to explicitly create an array of discrete values.
k = [1,2,4,7];
Now that you do this you can specify your loop like you had it with this small substitution for the values of k
kvalues = [1,2,4,7];
for i = 1:100
for k = 1:numel(kvalues)
b(i) = i * kvalues(k);
end
end
Notice that I have defined kvalues once outside of the loop so that it is not created every iteration through the outer loop (thanks to #dfri for pointing this oversight out)
The way that you have your loop written, you're actually over-writing the value of b(i) every time through the inner loop. I'm not sure if that's what you intended to do. If it is, then you can reduce your loop to the following:
b = k(end) * (1:100);
Otherwise, if you meant to have it be b(i,k) = i * k, you could rewrite this with bsxfun.
b = bsxfun(#mtimes, [1,2,4,7], (1:100).');
The syntax k=1:2:4:7 will not work as you intend. Usually we make use of the "two colon" syntax to describe a non-default (1) step size from the given start to end values, k = start:stepSize:end. Using an additional colon here even yields a Matlab warning ("third colon probably not intended?").
One possible workaround is to let your "non-continuous" indices reside in a vector and extract members of this vector in the inner for loop as follows
nonContIndex = [1; 2; 4; 7];
numIndices = numel(nonContIndex);
b = zeros(100,numIndices);
for i=1:100
for k=1:numIndices
b(i,k)=i*nonContIndex(k);
end
end
As noted by comments and the other answer: if b is simply a vector, your original loop will overwrite the b(i):th entry for each run of the inner loop. The above assumes that you in fact want a 2D matrix as a result.

Matlab - difficulty getting output for my function

I am trying to write a function transform(A) which when given a matrix A returns a new matrix. The new matrix should be obtained according to following:
if A has more than one row then interchange the first and second row. After this square the elements in the first row.
So far thats what I have written:
function[Anew] = transform(A)
dimension = size(A);
if dimension(1) > 1 %if there is more than 1 row
A([1 2],:)=A([2 1],:);
end
A(1,:,:) = A(1,:,:).^2 %squares elements in the first row
end
I tested my function by invoking it in matlab.
I noticed that because i dont have a semi colon next to A(1,:,:) = A(1,:,:).^2
I still obtain the desired result but not as output of the function.
I obtain A =
instead of Anew =
If i put a semi colon next to A(1,:,:) = A(1,:,:).^2; then I dont get an output at all.
Could you tell me what is wrong and what should I change in my program to obtain output as Anew?
Thank you
To return a value from a function in Matlab, you must directly assign to it.
In your case, you need to assign to Anew at the end of the operation (you could also technically just use that variable all-together).
function [Output1, Output2] = SomeFunction( ... )
% Do Some Work
% Store Output
Output1 = Result1(:,2) %some output
Output2 = Result2(3:end, :) %some other result
end
function[Anew] = transform(A)
dimension = size(A);
Anew = A;
if dimension(1) > 1 %if there is more than 1 row
Anew ([1 2],:)=Anew([2 1],:);
end
Anew(1,:,:) = Anew(1,:,:).^2; %squares elements in the first row
end