I want to use MATLAB's printmat do display a matrix with labels. But this doesn't work for complex numbers:
N = 5;
x = rand(N,1);
y = rand(N,1);
z = x + 1i*y;
printmat([x,y,z],'fftdemo','N=1 2 3 4 5','x y x+iy');
Output:
fftdemo =
x y x+iy
N=1 0.84072 0.34998 0.84072
2 0.25428 0.19660 0.25428
3 0.81428 0.25108 0.81428
4 0.24352 0.61604 0.24352
5 0.92926 0.47329 0.92926
As you can see the imaginary part of z isn't printed.
Is there a way to get Matlab to display complex numbers or another way to achieve this?
Any print function in matlab will only print real value of imaginary number. TO get both the parts you must call them explicitly.So correct usage would be
printmat([x,y,real(z),imag(z)],'fftdemo','N=1 2 3 4 5','x y x iy');
But this wont be of any use now since both are parts are getting printed twice.
Here is a slightly altered version of printmat that will print complex numbers. Feel free to fiddle around a bit more with it for better looks :)
function [] = printmat2(a,name,rlab,clab)
%PRINTMAT Print matrix with labels.
% PRINTMAT(A,NAME,RLAB,CLAB) prints the matrix A with the row labels
% RLAB and column labels CLAB. NAME is a string used to name the
% matrix. RLAB and CLAB are string variables that contain the row
% and column labels delimited by spaces. For example, the string
%
% RLAB = 'alpha beta gamma';
%
% defines 'alpha' as the label for the first row, 'beta' for the
% second row and 'gamma' for the third row. RLAB and CLAB must
% contain the same number of space delimited labels as there are
% rows and columns respectively.
%
% PRINTMAT(A,NAME) prints the matrix A with numerical row and column
% labels. PRINTMAT(A) prints the matrix A without a name.
%
% See also: PRINTSYS.
% Clay M. Thompson 9-24-90
% Copyright 1986-2002 The MathWorks, Inc.
% $Revision: 1.10 $ $Date: 2002/04/10 06:32:35 $
error(nargchk(1,4,nargin));
space = ' ';
[nrows,ncols] = size(a);
if nargin<2, name = []; end
if nargin==3, error('Wrong number of input arguments.'); end
if nargin<4,
rlab = []; clab = [];
for i=1:nrows, rlab = [rlab, sprintf('--%d--> ',i)]; end
for i=1:ncols, clab = [clab, sprintf('--%d--> ',i)]; end
rlab=rlab(1:length(rlab)-1);
clab=clab(1:length(clab)-1);
end
col_per_scrn=5;
len=12;
if (nrows==0)|(ncols==0),
if ~isempty(name), disp(' '), disp(sprintf('%s = ',name)), end
disp(' ')
disp(' []')
disp(' ')
return
end
% Remove extra spaces (delimiters)
ndx1 = find(clab==' ');
ndx2 = find([ndx1,0]==[-1,ndx1+1]);
if ~isempty(clab), clab(ndx1(ndx2))=[]; end
ndx1 = find(rlab==' ');
ndx2 = find([ndx1,0]==[-1,ndx1+1]);
if ~isempty(rlab), rlab(ndx1(ndx2))=[]; end
% Determine position of delimiters
cpos = find(clab==' ');
if length(cpos)<ncols-1, error('Not enough column labels.'); end
cpos = [0,cpos,length(clab)+1];
rpos = find(rlab==' ');
if length(rpos)<nrows-1, error('Not enough row labels.'); end
rpos = [0,rpos,length(rlab)+1];
col=1;
n = min(col_per_scrn-1,ncols-1);
disp(' ')
if ~isempty(name), disp(sprintf('%s = ',name)), end % Print name
while col<=ncols
% Print labels
s = space(ones(1,len+1));
for j=0:n,
lab = clab(cpos(col+j)+1:cpos(col+j+1)-1);
if length(lab)>len,
lab=lab(1:len);
else
lab=[space(ones(1,len-length(lab))),lab]; end
s= [s,' ',lab];
end
disp(setstr(s))
for i=1:nrows,
s = rlab(rpos(i)+1:rpos(i+1)-1);
if length(s)>len, s=s(1:len); else s=[space(ones(1,len-length(s))),s]; end
s = [' ',s];
for j=0:n,
element = a(i,col+j);
if imag(element) ~= 0
s=[s,sprintf('%12.5f + %12.5fi',[real(element) imag(element)])];
else
if element==0,
s=[s,' 0'];
elseif (element>=1.e6)|(element<=-1.e5)|(abs(element)<.0001)
s=[s,sprintf(' %12.5e',element)];
else
s=[s,sprintf(' %12.5f',element)];
end
end
end
disp(s)
end % for
col = col+col_per_scrn;
disp(' ')
if (ncols-col<n), n=ncols-col; end
end % while
% end printmat
Related
enter image description here
I am having difficulty with my code aligning right shifted waveforms by the minimum peak point. In the left shifted, I copy the difference in indices between the desired minimum point and the given one to left of the waveform, and then delete those extra points after once this aligns the waveform. However, the same technique is not working for the right shifted ones. Any help would be much appreciated! Input (vals) is any n x 97 matrix.
function [vals] = align_wvs(wvs)
%Align_wvs - Align waveforms to minimum point
%
%align_wvs(wvs)
%
%wvs - matrix of waveforms
%
%Returns 'vals' - newly aligned matrix of waveforms
wvfrms = (wvs*10^6); %convert to microvolts
wvfrms = wvfrms(:,all(~isnan(wvfrms)));
min_pt = min(wvfrms(:)); %find minimum point in wvs
[~,col] = find(wvfrms==min_pt); %find index of min poin
if numel(col)>1
col = col(1);
end
%and that of other wvfrms
vals = zeros(size(wvfrms)); %matrix of size wvfrms, vals
for i = 1:size(vals,1) %for length of input
vals(i,:) = wvfrms(i,:); %copy og wvfrm into vals
nums = vals(i,:); %get second copy
ind_min = min(nums);
[~,colmin] = find(nums==ind_min);
diff_col = col-colmin;
if (diff_col~=0) %if difference is not = 0
if (diff_col>0) %if wvfrm is shifted to the left
inds = nums(1:diff_col); %copy first n values of nums, where n is diff_rows
new_length = length(nums)+length(inds); %extend wvfrm by amount ind
new_vals = zeros(1,new_length); %create new array of size new_length
new_vals(1:(diff_col)) = inds; %add inds to begining of new array
new_vals(diff_col+1:end) = nums; %add nums to rest of array
new_vals(1:(diff_col)) = [];%delete diff_rows-1 values from end
vals(i,:) = new_vals; %add to values
else %if wvfrm is shifted to the right
inds = nums(end+(diff_col+1):end); %copy last n values of nums, where n is diff_rows
new_length = length(nums)+length(inds); %extend wvfrm by amount ind
new_vals = zeros(1,new_length); %create new array of size new_length
new_vals(end+(diff_col+1):end) = inds;%add inds to end of new array
new_vals(1:(end+(diff_col))) = nums;%add nums to rest of array
new_vals(1:(diff_col*-1)) = []; %delete diff_rows-1 values from begining
vals(i,:) = new_vals; %add to values
end
end
end
end
List item
Does replacing the if (diff_col~=0) block with the following work?
if (diff_col~=0)
if (diff_col>0)
vals(i,:) = [zeros(1,diff_col) nums(1:(end-diff_col))];
else
vals(i,:) = [nums((-diff_col+1):end) zeros(1,-diff_col)];
end
end
suppose we have following script for prime factorization
z=input('enter your number : ');
for ii=2:z
s=0;
while z/ii==floor(z/ii) % check if z is divisible by ii
z=z/ii;
s=s+1;
end
if s>0
str = [num2str(ii) '^' num2str(s) ];
disp(str) ;
% If z = 1, no more divisions are necessary,
% thus breaks the loop and quits
if z == 1
break
end
end
end
but output of this code is not formatted well,for instance
>> integer_factorization
enter your number : 30
2^1
3^1
5^1
how can i do so that i got
30=2^1*3^1*5^1?
thanks in advance
This is fairly straightforward: Use fprintf(''); instead to print/display the factors.
z=input('enter your number : ');
ans='' %the final answer string
for ii=2:z
s=0;
while z/ii==floor(z/ii) % check if z is divisible by ii
z=z/ii;
s=s+1;
end
if s>0
str = [num2str(ii) '^' num2str(s) ];
%disp(str) ;
strcat(ans,'*',str); %concats the * str as per requirement.
% If z = 1, no more divisions are necessary,
% thus breaks the loop and quits
if z == 1
break
end
end
end
ans=ans(2:end); % to remove the first *
fprintf(ans); % can even use the disp() function.
So, basically, added a string to append the factors into it and display at the end, outside of the loops.
You can simply create a string and add your numbers to the string and finally print the string. something as follow:
z=input('enter your number : ');
for ii=2:z
s=0;
while z/ii==floor(z/ii) % check if z is divisible by ii
z=z/ii;
s=s+1;
end
if s>0
str = str + [num2str(ii) '^' num2str(s) '*' ];%only update
% If z = 1, no more divisions are necessary,
% thus breaks the loop and quits
if z == 1
break
end
end
str = str(0,str.size -1) %use proper command to remove the last * from your string result
disp(str) ; %display the str at the end in one line
end
Litle modification of your code.
z=input('enter your number : ');
for ii=2:z
s=0;
while z/ii==floor(z/ii) % check if z is divisible by ii
z=z/ii;
s=s+1;
end
if s>0
str += [num2str(ii) '^' num2str(s) ];
% If z = 1, no more divisions are necessary,
% thus breaks the loop and quits
if z == 1
break
else
str+='*';
end
end
end
disp(str);
This could work! Just with a few changes to your code
z=input('enter your number : ');
str=[num2str(z) '='];
first=0;
for ii=2:z
s=0;
while z/ii==floor(z/ii) % check if z is divisible by ii
z=z/ii;
s=s+1;
end
if s>0
if first==0
str=[str num2str(ii) '^' num2str(s)];
first=1;
else
str=[str '*' num2str(ii) '^' num2str(s)];
if z == 1
break
end
end
end
end
first of all thanks everyone for your afford, here is my final solution
z=input('enter your number : ');
string='';
for ii=2:z
s=0;
while z/ii==floor(z/ii) % check if z is divisible by ii
z=z/ii;
s=s+1;
end
if s>0
str =[num2str(ii) '^' num2str(s) ];
string=strcat(string,str);
string= strcat(string,'*');
% If z = 1, no more divisions are necessary,
% thus breaks the loop and quits
if z == 1
break
end
end
end
string=string(1:end-1);% remove last sign of multiplicaiton
fprintf('prime factorization is %s\n',string);
here is several examples
>> integer_factorization
enter your number : 30
prime factorization is 2^1*3^1*5^1
another
>> integer_factorization
enter your number : 35
prime factorization is 5^1*7^1
and last one
>> integer_factorization
enter your number : 100
prime factorization is 2^2*5^2
I m working on this project where i have implemented the dictionary as well as the OMP algorithm now i cant understand how to implement on lena image.i am providing my code over here.
%function [X_pr pp]=ompmod_pred2(D1,a1,sl,errorGoal)
%____________________________________________________
%prediction using (Aurelie method)
% D1=Dictionary;
%a1=image block of size (16X16);
%sl=sparsity label
%X_pr=predicted block
s=8;
%D=first 3:4 of D1
D=D1(1:3*s^2,:);
%D2=last 1:4 of D1
D2=D1(3*s^2+1:4*s^2,:);
%X_ac=block to be predicted
X_ac=a1(9:16,9:16);
%X1=reshape a1 to column
Y1=im2col(a1,[s,s],'distinct');
X1=im2col(Y1,[s^2,4],'distinct');
%X=first 3:4 of X1
X=X1(1:3*s^2,1);
%X2=last 1:4 of X1
X2=X1(3*s^2+1:4*s^2,1);
%___________________________________
%A2=calculation of solution vector at
%diffrent sparsity label using OMP
%___________________________________
[n,P]=size(X);
[n,K]=size(D);
E2 = errorGoal^2*n;
for s1=1:s1
maxNumCoef = s1;
A2(:,1)= zeros(size(D,2),size(X,2));
errorRes = X; % new entry
for k=1:1:P,
x=X(:,k);
residual=x;
indx = [];
a = [];
% currResNorm2 = sum(residual.^2); % creates problem for complex vectors
currResNorm2 = residual'*residual; %'
j = 0;
while currResNorm2>E2 & j < maxNumCoef,
j = j+1;
proj=D'*residual; %'
pos=find(abs(proj)==max(abs(proj)));
pos=pos(1);
indx(j)=pos;
z1=pinv(D(:,indx(1:j)));
a=pinv(D(:,indx(1:j)))*x;
residual=x-D(:,indx(1:j))*a;
% currResNorm2 = sum(residual.^2);
currResNorm2 = residual'*residual; %'
end;
if (length(indx)>0)
%_____________________________________
l1=length(indx);
for k1=1:l1
for k2=1:K
if k2==indx(1,k1)
A1(k2,k1)=a(k1,1);
else A1(k2,k1)=0;
end
end
if l1==1
A=A1;
else
A=sum(A1')';
end
%_______________________________________
errorRes(:,k)=residual; % new entry
end
end;
end
A2=[A2 A];
end
%________________________________________________
%X3=calculation of error at different sparsity label
l1=length(indx);
for k1=1:l1
X3(k1)=((D2*A2(:,k1+1))-X2)'*((D2*A2(:,k1+1))-X2); %'
end
% %________________________________________________
%pv=minimum error,pp=iteration
[pv pp]=min(X3);
%X_pr=predicted block
X_pr1=D2*A2(:,pp+1);
X_pr=col2im(X_pr1,[8 8],[8 8],'distinct');
%_________________________________________________
return;
Here is my code for creating a dictionary.
function[D]=dict1(s)
%Generate DCT Dictionary of size (s^2 x s^2)
a=idct(eye(s));
for k1=1:s^2
if rem(k1,s)==0
b(:,(k1-1)*s+1:k1*s)=a(:,ceil(k1/s))*a(:,1)'; %'
else
b(:,(k1-1)*s+1:k1*s)=a(:,ceil(k1/s))*a(:,rem(k1,s))'; %'
end
end
D1=im2col(b,[s/2 s/2],'distinct');
D=im2col(D1,[s^2/4 4],'distinct');
end
where s=16
please help me .
I have an Image which is 1944(R) x 2592 (C). I would like to take one column at a time; treating each column as an Image and calculate how many pixels among each row of that column contains value > half(max) value of that column. Those number of pixels are to be written to the excel sheet corresponding to it's respective column.
Image: the image
Here is what I have tried so far, I am not able to write it successfully.
clc;
sig = rgb2gray(imread('1.bmp')); % read in the image.
% imshow(sig);
ArraySize = size(sig); %1944(R) x 2592 (C)
[maxval, maxloc] = max(sig(:)); % Gives the max and the location
maxval; % max value
[maxloc_row, maxloc_col] = ind2sub(size(sig), maxloc); % convert logical
%-------------------------------------------------------------------%
% Count pixels through each column > half(max) value of that column
%-------------------------------------------------------------------%
newfilename = 'Results.csv'; % write new values to .csv files
Array = zeros(2592,2);
% % R = Array(:,1);
% y = Array(:,2);
for a = 1: 2592% maxloc_row = 635 maxloc_col = 1094
[a_maxval, a_maxloc] = max(sig(:,a)); % search max among every column.
% maxloc is the row at which maxval is.
newval = a_maxval/2; % averaged max value
% New structure for find width
x = 0;
x = Array(:, 1);
for b = 1: 1944 % maxloc_row = 635 maxloc_col = 1094
% R = b;
if sig(b,a) > newval
x=x+1;
end
end % End row search
x;
% y = x*(2.2); % pixels into microns
output = [num2cell(x)];
xlswrite(newfilename, output);
end % End column search
I think csvwrite can write data to csv file. Here's what you can try:
place output = []; somewhrere at top, says below clc;
then, replace
output = [num2cell(x)]; with output = [output x];
and
xlswrite(newfilename, output); with csvwrite(newfilename, output); but place it at the end of program because output has all x inside.
I have tried and it works.
I am doing a basic MATLAB online-course and in one part of the last assignment I need to "create a line graph from an expression based on user input".
My interpretation is that a user should be able to type in an expression f(x)=... such as:
3x^2+3x+c
I have successfully written code that will ask the user for the number of variables (numbers before the x:s) and exponents and if there is an constant or not.
Also, my code then generates variables from user input (input: string -> genvarname), and then assigns a correct value to it also from user input via the eval command/function.
Lastly, I have done an for-loop and used exist to determine if a variable exists.
My question now is, how can I use the result from exist (eg = 1) in a if-loop to access the variable and store it in an vector.
That way I believe I can with another for loop calculate values for y. the x-values are just x = -50:1:50, but if there are any suggestions for how to calculate y simpler than please tell me.
I have gained lots of information from reading StackOverflow posts, I just hope my question is relevant, and helpful. :)
EDIT:
%% Initial questions
IN = input('Give foo: [på formen A1x^a1+A2x^a2...Nx^n+KONST] ','s');
if isempty(IN)
IN = '3x^2+4x+2';
end
disp(['Du vill plotta ' IN]);
vars_qty = input('Hur många variabler har du? ');
if isempty(vars_qty)
vars_qty = 2;
end
exps_qty = vars_qty;
const = input('Har du en konstant på slutet? [Ja/Nej] ','s');
if isempty(const)
const = 'Ja';
end
disp(' ');
%vars_vector_name = cell(vars_qty, 1); % cell array with variable names
vars_vector_vals = zeros(vars_qty, 1); % vector with variable values
%exps_vector_name = cell(exps_qty, 1); % cell array with exponent names
exps_vector_vals = zeros(exps_qty, 1); % vector with exponent values
%% Assigning vectors
x = -50:1:50; % x vector
A = zeros(vars_qty, 1);
a = zeros(vars_qty, 1);
%% Assigning variable and exponent names + create variables and set a value to it
for i = 1:vars_qty
disp(['Variabel ' num2str(i) ':']);
% vars_vector_name(i, 1) = cellstr(input('Var god och namnge variabeln [A1,B..] ', 's')); %
... does not like an empty input
var = input('Var god och namnge variabeln [A1,A2...An] ', 's');
% if isempty(var)
% var = ['A',num2str(i)];
% end
vars_vector_vals(i, 1) = input('Vad är värdet på variabeln? '); %
... does not like an empty input
% if isempty(vars_vector_vals(i, 1))
% vars_vector_vals(i, 1) = i;
% end
vars_gen = genvarname( var );
eval([ var '= vars_vector_vals(i, 1);' ]);
vars_exist = exist( ['A',num2str(i)], 'var'); % isvarname( num2str(vars_gen) ); % num2str(vars_gen)
if vars_exist == 1
disp('Exist!');
% A(i, 1) = vars_gen;
% A(i, 1) = eval([ var '= vars_vector_vals(i, 1);' ]);
else
...
end
disp(['Exponent ' num2str(i) ':']);
exps = input('Var god och namnge exponenten [a1,a2...an & a2<a1] ', 's');
% if isempty(exps)
% exp = ['a',num2str(i)];
% end
exps_vector_vals(i, 1) = input('Vad är värdet på exponenten? '); %
... does not like an empty input
% if isempty(exps_vector_vals(i, 1))
% exps_vector_vals(i, 1) = i;
% end
exps_gen = genvarname( exps );
eval([ exps '= exps_vector_vals(i, 1);' ]);
exps_exist = exist( ['a',num2str(i)], 'var'); % isvarname( num2str(exps_gen) ); % num2str(exps_gen)
if exps_exist == 1
disp('Exist!');
% a(i, 1) = exps_gen;
% a(i, 1) = eval([ exps '= exps_vector_vals(i, 1);' ]);
else
...
end
end
% exps_vector_name(j, 1) = cellstr(input('Var god och namnge exponenten [a,b.. & b<a] ', 's')); %
... does not like an empty input
if strcmp(const,'Ja')
disp(' ');
const_scalar = input('Vad är värdet på konstanten? '); % scalar with constant
else
const_scalar = 0;
end
%gen_vars = genvarname({ (vars_vector_name(:,1)) });
%gen_exps = genvarname({ (exps_vector_name(:,1)) });
%eval([ gen_vars '= vars_vector_vals(:,1);' ]); % doesn't like a cell array
%eval([ gen_exps '= exps_vector_vals(:,1);' ]); % doesn't like a cell array
y = zeros(vars_qty, 1);
% for k = 1:vars_qty
% y(k, 1) =
% end
MATLAB's EXIST command is a little tricky to use correctly because it checks so many things. Here's how I would write this:
userVarName = ...
if exist(userVarName, 'var') == 1 % Return value 1 indicates a variable.
varValue = eval(userVarName);
else
error('Variable "%s" does not exist.', userVarName);
end
EDIT
Looks like the relevant portion of your code needs to be adapted like so:
vars_name = ['A', num2str(j)];
if exist(vars_name, 'var') == 1
A(j, 1) = eval(vars_name);
end