Tag Archives: matlab
Open data in File as per user input
Hello, I am trying to get input from user to load a file and then ask which variable from the file would they like to plot. The input file will be a .mat file and it is a 1×1 struct file with various 2 double series data in it.
When I run this, the error says: Unrecognized field name "x"
Here is my code:
filename=input(‘Input File Name n’,’s’);
file = load(filename);
x=string(input(‘Variable? n’,’s’));
plot(file.x)Hello, I am trying to get input from user to load a file and then ask which variable from the file would they like to plot. The input file will be a .mat file and it is a 1×1 struct file with various 2 double series data in it.
When I run this, the error says: Unrecognized field name "x"
Here is my code:
filename=input(‘Input File Name n’,’s’);
file = load(filename);
x=string(input(‘Variable? n’,’s’));
plot(file.x) Hello, I am trying to get input from user to load a file and then ask which variable from the file would they like to plot. The input file will be a .mat file and it is a 1×1 struct file with various 2 double series data in it.
When I run this, the error says: Unrecognized field name "x"
Here is my code:
filename=input(‘Input File Name n’,’s’);
file = load(filename);
x=string(input(‘Variable? n’,’s’));
plot(file.x) file, user input MATLAB Answers — New Questions
WHAT IMAGE IS THIS?
-Ruído gaussiano: é um tipo de ruído aditivo que segue uma distribuição normal. É comum em imagens capturadas com sensores eletrônicos, como câmeras digitais.
-Ruído sal e pimenta: é um tipo de ruído impulsivo que adiciona pixels brancos ou pretos aleatoriamente na imagem. É comum em imagens capturadas em ambientes com baixa iluminação ou em transmissões de imagens.
– Ruído de Poisson: é um tipo de ruído que ocorre em imagens com baixa intensidade de luz, como imagens médicas ou astronômicas. É causado pela natureza probabilística da captura de fótons.
– Ruído de amplificador: é um tipo de ruído aditivo que ocorre em imagens capturadas com amplificadores eletrônicos, como em câmeras digitais.
– Ruído de tiro: é um tipo de ruído aditivo que ocorre em imagens capturadas com sensores eletrônicos, como câmeras digitais. É causado pela variação aleatória na quantidade de elétrons gerados pelos fotossensores.
– Ruído de quantização: é um tipo de ruído aditivo que ocorre em imagens digitais devido à limitação da resolução do sistema de aquisição de imagens.
– Granulação de filme: é um tipo de ruído aditivo que ocorre em imagens capturadas em filmes fotográficos. É causado pela variação aleatória na densidade de grãos de prata no filme.
– Ruído isotrópico: é um tipo de ruído aditivo que ocorre em imagens digitais devido à variação aleatória na intensidade dos pixels. – Ruído multiplicativo: é um tipo de ruído que ocorre em imagens capturadas por sistemas de radar ou ultrassom. É causado pela reflexão aleatória das ondas sonoras ou eletromagnéticas.
– Ruído periódico: é um tipo de ruído que ocorre em imagens digitais devido à interferência de sinais periódicos, como linhas de energia elétrica ou sinais de televisão.
Filtro de média: é uma técnica de filtragem simples que substitui cada pixel na imagem pela média dos pixels em sua vizinhança. É eficaz para remover ruído gaussiano e ruído de quantização.
Filtro de mediana: é uma técnica de filtragem que substitui cada pixel na imagem pela mediana dos pixels em sua vizinhança. É eficaz para remover ruído impulsivo, como ruído sal e pimenta.
– Filtro de Wiener: é uma técnica de filtragem que usa uma estimativa da densidade espectral de potência do sinal de imagem e do ruído para remover o ruído. É eficaz para remover ruído gaussiano.
Filtro de Kalman: é uma técnica de filtragem que usa um modelo estatístico para estimar o sinal de imagem original a partir do sinal degradado. É eficaz para remover ruído gaussiano e ruído de amplificador.
– Filtro de Anisotrópico: é uma técnica de filtragem que usa uma equação diferencial parcial para remover o ruído enquanto preserva as bordas da imagem. É eficaz para remover ruído gaussiano e ruído de amplificador.
– Filtro de média: – Vantagens: é uma técnica de filtragem simples e fácil de implementar. É eficaz para remover ruído gaussiano e ruído de quantização. – Desvantagens: pode suavizar demais as bordas da imagem e reduzir a nitidez da imagem.
– Filtro de mediana: – Vantagens: é uma técnica de filtragem robusta que é eficaz para remover ruído impulsivo, como ruído sal e pimenta. Preserva as bordas da imagem. – Desvantagens: pode introduzir artefatos na imagem, como halos ao redor das bordas.
– Filtro de Wiener: – Vantagens: é uma técnica de filtragem que usa uma estimativa da densidade espectral de potência do sinal de imagem e do ruído para remover o ruído. É eficaz para remover ruído gaussiano. – Desvantagens: pode introduzir artefatos na imagem, como bordas borradas.
– Filtro de Kalman: – Vantagens: é uma técnica de filtragem que usa um modelo estatístico para estimar o sinal de imagem original a partir do sinal degradado. É eficaz para remover ruído gaussiano e ruído de amplificador. – Desvantagens: é computacionalmente intensivo e pode ser sensível a erros no modelo estatístico.
– Filtro de Anisotrópico: – Vantagens: é uma técnica de filtragem que usa uma equação diferencial parcial para remover o ruído enquanto preserva as bordas da imagem. É eficaz para remover ruído gaussiano e ruído de amplificador. – Desvantagens: é computacionalmente intensivo e pode introduzir artefatos na imagem, como bordas serrilhadas.
Filtro Inverso: Busca compensar ou inverter os efeitos de um sistema, sendo usado em processamento de sinal para melhorar a qualidade. Filtro Pseudo-Inverso: Similar ao inverso, mas aplicado em situações em que a matriz não é diretamente inversível. Usa técnicas alternativas para obter uma solução aproximada.
Filtro de Salsicha: Geralmente referido como filtro passa-baixa, atenua as frequências mais altas em um sinal, destacando as mais baixas. Filtro de Mínimos Quadrados Restrito: Utilizado para ajustar um modelo aos dados minimizando a soma dos quadrados das diferenças entre os valores previstos e observados, com restrições adicionais.
Filtro Máximo: Maximiza uma determinada característica, sendo aplicado em diversos contextos, como processamento de imagem e comunicações.
Filtro Mínimo: Minimiza uma característica específica, frequentemente usado em problemas de otimização. Filtro Mediano: Substitui cada pixel em uma imagem pela mediana dos valores dos pixels vizinhos, sendo eficaz para remover ruídos.
Filtro Médio: Calcula a média dos valores em uma região específica, útil para suavizar imagens ou sinais.
Filtro Adaptativo: Ajusta seus parâmetros automaticamente em resposta às características do sinal ou ambiente, proporcionando flexibilidade em várias condições.
Filtro Inverso: Vantagens: Pode oferecer uma compensação precisa. Desvantagens: Sensível a ruídos, instabilidades numéricas.
Filtro Pseudo-Inverso: Vantagens: Útil quando a matriz não é inversível. Desvantagens: A solução é aproximada, não ideal para todos os casos. Filtro de Salsicha: Vantagens: Remove ruídos de alta frequência. Desvantagens: Pode causar suavização excessiva e perda de detalhes.
Filtro de Mínimos Quadrados Restrito: Vantagens: Lida com restrições específicas. Desvantagens: Pode ser sensível a condições iniciais, computacionalmente exigente.
Filtro Máximo: Vantagens: Destaca características específicas. Desvantagens: Pode realçar ruídos indesejados.
Filtro Mínimo: Vantagens: Útil para remoção de ruídos. Desvantagens: Suaviza detalhes importantes.
Filtro Mediano: Vantagens: Eficaz na remoção de ruídos impulsivos. Desvantagens: Pode não ser tão eficaz para outros tipos de ruídos.
Filtro Médio: Vantagens: Suaviza sinais preservando tendências. Desvantagens: Pode não funcionar bem com outliers.
Filtro Adaptativo: Vantagens: Ajusta-se automaticamente a mudanças nas condições. Desvantagens: Complexidade computacional, sensibilidade a condições extremas.
——————————————————————————————————————————————————————————————-
LIMIARIZAÇÃO=
% Carregar a imagem
f = imread(‘football.jpg’); % Substitua ‘football.jpg’ pelo nome da sua imagem
% Converter para escala de cinza
grayImage = rgb2gray(f);
% Definir o limiar
threshold = 0.5; % Pode ser um valor entre 0 e 1, ou um valor específico para imagens em 8 bits (0 a 255)
% Limiarizar a imagem
binaryImage = imbinarize(grayImage, threshold);
% Exibir as imagens
figure;
subplot(1, 2, 1);
imshow(grayImage);
title(‘Imagem em Escala de Cinza’);
subplot(1, 2, 2);
imshow(binaryImage);
title(‘Imagem Limiarizada’);
————————————————————————————————–
ESCALA DE CINZA – BINARIZAÇÃO
f=rgb2gray(imread(‘peppers.png’));
bw=im2bw(f,0.5);
imshow(bw)
m=127;
E=20;
g=1./(1+(m./(double(f)+ eps)).^E)
subplot(1,2,1);imshow(f);subplot(1,2,2);imshow(g);
——————————————————————————————-
AJUSTE DE CONTRASTE
f=rgb2gray(imread(‘peppers.png’));
bw=im2bw(f,0.5);
imshow(bw)
g1= imadjust(f,[0 1],[1 0],0.6);
g2= imadjust(f,[0 1],[1 0],1);
g3= imadjust(f,[0 1],[1 0 ],4);
subplot(1,3,1)
imshow(g1)
subplot(1,3,2)
imshow(g2)
subplot(1,3,3)
imshow(g3)
————————————————————————————————-
imread(‘peppers.png’);
g1= imadjust(f,[0 1],[1 0],0.6);
g2= imadjust(f,[0 1],[1 0],1);
g3= imadjust(f,[0 1],[1 0],4);
subplot(1,3,1)
imshow(g1)
subplot(1,3,2)
imshow(g2)
subplot(1,3,3)
imshow(g3)
——————————————————————————————————————
i=imread(‘peppers.png’);
g=rgb2gray(i);
s=im2uint8(mat2gray(log(1+double(g))));
subplot(1,3,1);imshow(i);subplot(1,3,2);imshow(g);
subplot(1,3,3);imshow(s);
——————————————————————————————————————
f=rgb2gray(imread(‘peppers.png’));
[P, Q]=size(f);
F=fft2(f, 2*P, 2*Q); F=abs(F) ;Fc=fftshift(F);
subplot(1,3,1);imshow(f);subplot(1,3,2);imshow(Fc,[]);
s=im2uint8(mat2gray(log( 1 + double(Fc))));
subplot(1,3,3); imshow(s,[]);
——————————————————————————————————————
fruido=rgb2gray(imread( "boy-6281260_640.jpg"));
w2= (1/64)*ones(8);
g2=im2uint8(mat2gray(imfilter(double(fruido),w2)));
subplot(1,2,1);imshow(fruido);subplot(1,2,2);imshow(g2);
——————————————————————————————————————
A=imread("boy-6281260_640.jpg");
subplot(1,2,1); imshow (A);
k= fspecial(‘average’, [9 9]);
B=imfilter(A, k,"symmetric");
subplot(1,2,2); imshow(B);
————————————————————————————————-
I=rgb2gray(imread(‘boy-6281260_640.jpg’));
subplot(1,3,1), imshow(I);
Isp = imnoise (I, ‘salt & pepper’, 0.03);
subplot(1,3,2), imshow(Isp);
Ig = imnoise (I,’gaussian’, 0.02);
subplot(1,3,3), imshow(Ig);
————————————————————————————————–
I=rgb2gray(imread(‘boy-6281260_640.jpg’));
subplot(1,3,1), imshow(I);
Isp = imnoise (I, ‘salt & pepper’, 0.03);
subplot(1,3,2), imshow(Isp);
Ig = imnoise (I,’gaussian’, 0.02);
subplot(1,3,3), imshow(Ig);
K=ones (3,3)/9;
I_m = imfilter(I,k);
Isp_m = imfilter(Isp,k);
Ig_m = imfilter(Ig,k);
subplot(1,3,1), imshow(I_m);
subplot(1,3,2), imshow(Isp_m);
subplot(1,3,3), imshow(Ig_m);
%%
I_m = medfilt2(I,[3 3]);
Isp_m = medfilt2(Isp,[3 3]);
Ig_m = medfilt2(Ig, [3 3]);
subplot(1,3,1), imshow(I_m);
subplot(1,3,2), imshow(Isp_m);
subplot(1,3,3), imshow(Ig_m);
%%
I_m = ordfilt2(I,25,ones(5,5));
Isp_m = ordfilt2(Isp,25,ones(5,5));
Ig_m = ordfilt2(Ig,25,ones(5,5));
subplot(1,3,1), imshow(I_m);
subplot(1,3,2), imshow(Isp_m);
subplot(1,3,3), imshow(Ig_m);
——————————————————-
Guide —
function varargout = EstudandoThomas(varargin)
gui_Singleton = 1;
gui_State = struct(‘gui_Name’, mfilename, …
‘gui_Singleton’, gui_Singleton, …
‘gui_OpeningFcn’, @EstudandoThomas_OpeningFcn, …
‘gui_OutputFcn’, @EstudandoThomas_OutputFcn, …
‘gui_LayoutFcn’, [] , …
‘gui_Callback’, []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code – DO NOT EDIT
% — Executes just before EstudandoThomas is made visible.
function EstudandoThomas_OpeningFcn(hObject, eventdata, handles, varargin)
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% — Outputs from this function are returned to the command line.
function varargout = EstudandoThomas_OutputFcn(hObject, eventdata, handles)
varargout{1} = handles.output;
% — Executes on button press in Abrir.
function Abrir_Callback(hObject, eventdata, handles)
global im1
[filename,path]=uigetfile(‘*.jpg;*.gif;*.tif;*.png’,’Selecione Imagem’);
im1=imread(strcat(path,filename));
axes(handles.axes1);
imshow(im1);
% — Executes on button press in Cinza.
function Cinza_Callback(hObject, eventdata, handles)
global im1 gray
gray=rgb2gray(im1);
axes(handles.axes2);
imshow(gray);
% — Executes on button press in Histograma.
function Histograma_Callback(hObject, eventdata, handles)
global gray
axes(handles.axes4);
imhist(gray);
% — Executes on button press in Equalizar.
function Equalizar_Callback(hObject, eventdata, handles)
global gray
axes(handles.axes5);
eq=histeq(gray);
imhist(eq);
% — Executes on button press in Salvar.
function Salvar_Callback(hObject, eventdata, handles)
F=getimage(handles.axes3);
FileName=uiputfile({‘*.jpg;*.tif;*.png;*.gif’,’All Image Files’;…
‘*.*’,’All Files’ },’Save Image’,…
‘C:Worknewfile.jpg’)
imwrite(F,FileName,’jpg’);
% — Executes on button press in Reset.
function Reset_Callback(hObject, eventdata, handles)
cla(handles.axes1,’reset’);
cla(handles.axes2,’reset’);
cla(handles.axes3,’reset’);
cla(handles.axes4,’reset’);
cla(handles.axes5,’reset’);
% — Executes on button press in Media.
function Media_Callback(hObject, eventdata, handles)
global gray n
axes(handles.axes3);
w1=(1/(n^2))*ones(n);
g1=im2uint8(mat2gray(imfilter(double(gray),w1)));
imshow(g1);
% — Executes on button press in Mediana.
function Mediana_Callback(hObject, eventdata, handles)
global gray n
axes(handles.axes3);
posicao=double((n^2-1)/2)+1;
g2=ordfilt2(gray,posicao,true(n));
imshow(g2);
% — Executes on button press in Maximo.
function Maximo_Callback(hObject, eventdata, handles)
global gray n
axes(handles.axes3);
g2=ordfilt2(gray,n*n,true(n));
imshow(g2);
% — Executes on button press in Minimo.
function Minimo_Callback(hObject, eventdata, handles)
global gray n
axes(handles.axes3);
g2=ordfilt2(gray,1,true(n));
imshow(g2);
function Matriz_Callback(hObject, eventdata, handles)
global n
str=get(handles.Matriz,’String’);
n=str2double(str);
% — Executes during object creation, after setting all properties.
function Matriz_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,’BackgroundColor’), get(0,’defaultUicontrolBackgroundColor’))
set(hObject,’BackgroundColor’,’white’);
end
% — Executes on button press in Binario.
function Binario_Callback(hObject, eventdata, handles)
global gray
binario=im2bw(gray);
axes(handles.axes3);
imshow(binario)
% — Executes on button press in Negativo.
function Negativo_Callback(hObject, eventdata, handles)
global gray
neg = imadjust(gray, [0 1], [1 0],1);
axes(handles.axes3);
imshow(neg);-Ruído gaussiano: é um tipo de ruído aditivo que segue uma distribuição normal. É comum em imagens capturadas com sensores eletrônicos, como câmeras digitais.
-Ruído sal e pimenta: é um tipo de ruído impulsivo que adiciona pixels brancos ou pretos aleatoriamente na imagem. É comum em imagens capturadas em ambientes com baixa iluminação ou em transmissões de imagens.
– Ruído de Poisson: é um tipo de ruído que ocorre em imagens com baixa intensidade de luz, como imagens médicas ou astronômicas. É causado pela natureza probabilística da captura de fótons.
– Ruído de amplificador: é um tipo de ruído aditivo que ocorre em imagens capturadas com amplificadores eletrônicos, como em câmeras digitais.
– Ruído de tiro: é um tipo de ruído aditivo que ocorre em imagens capturadas com sensores eletrônicos, como câmeras digitais. É causado pela variação aleatória na quantidade de elétrons gerados pelos fotossensores.
– Ruído de quantização: é um tipo de ruído aditivo que ocorre em imagens digitais devido à limitação da resolução do sistema de aquisição de imagens.
– Granulação de filme: é um tipo de ruído aditivo que ocorre em imagens capturadas em filmes fotográficos. É causado pela variação aleatória na densidade de grãos de prata no filme.
– Ruído isotrópico: é um tipo de ruído aditivo que ocorre em imagens digitais devido à variação aleatória na intensidade dos pixels. – Ruído multiplicativo: é um tipo de ruído que ocorre em imagens capturadas por sistemas de radar ou ultrassom. É causado pela reflexão aleatória das ondas sonoras ou eletromagnéticas.
– Ruído periódico: é um tipo de ruído que ocorre em imagens digitais devido à interferência de sinais periódicos, como linhas de energia elétrica ou sinais de televisão.
Filtro de média: é uma técnica de filtragem simples que substitui cada pixel na imagem pela média dos pixels em sua vizinhança. É eficaz para remover ruído gaussiano e ruído de quantização.
Filtro de mediana: é uma técnica de filtragem que substitui cada pixel na imagem pela mediana dos pixels em sua vizinhança. É eficaz para remover ruído impulsivo, como ruído sal e pimenta.
– Filtro de Wiener: é uma técnica de filtragem que usa uma estimativa da densidade espectral de potência do sinal de imagem e do ruído para remover o ruído. É eficaz para remover ruído gaussiano.
Filtro de Kalman: é uma técnica de filtragem que usa um modelo estatístico para estimar o sinal de imagem original a partir do sinal degradado. É eficaz para remover ruído gaussiano e ruído de amplificador.
– Filtro de Anisotrópico: é uma técnica de filtragem que usa uma equação diferencial parcial para remover o ruído enquanto preserva as bordas da imagem. É eficaz para remover ruído gaussiano e ruído de amplificador.
– Filtro de média: – Vantagens: é uma técnica de filtragem simples e fácil de implementar. É eficaz para remover ruído gaussiano e ruído de quantização. – Desvantagens: pode suavizar demais as bordas da imagem e reduzir a nitidez da imagem.
– Filtro de mediana: – Vantagens: é uma técnica de filtragem robusta que é eficaz para remover ruído impulsivo, como ruído sal e pimenta. Preserva as bordas da imagem. – Desvantagens: pode introduzir artefatos na imagem, como halos ao redor das bordas.
– Filtro de Wiener: – Vantagens: é uma técnica de filtragem que usa uma estimativa da densidade espectral de potência do sinal de imagem e do ruído para remover o ruído. É eficaz para remover ruído gaussiano. – Desvantagens: pode introduzir artefatos na imagem, como bordas borradas.
– Filtro de Kalman: – Vantagens: é uma técnica de filtragem que usa um modelo estatístico para estimar o sinal de imagem original a partir do sinal degradado. É eficaz para remover ruído gaussiano e ruído de amplificador. – Desvantagens: é computacionalmente intensivo e pode ser sensível a erros no modelo estatístico.
– Filtro de Anisotrópico: – Vantagens: é uma técnica de filtragem que usa uma equação diferencial parcial para remover o ruído enquanto preserva as bordas da imagem. É eficaz para remover ruído gaussiano e ruído de amplificador. – Desvantagens: é computacionalmente intensivo e pode introduzir artefatos na imagem, como bordas serrilhadas.
Filtro Inverso: Busca compensar ou inverter os efeitos de um sistema, sendo usado em processamento de sinal para melhorar a qualidade. Filtro Pseudo-Inverso: Similar ao inverso, mas aplicado em situações em que a matriz não é diretamente inversível. Usa técnicas alternativas para obter uma solução aproximada.
Filtro de Salsicha: Geralmente referido como filtro passa-baixa, atenua as frequências mais altas em um sinal, destacando as mais baixas. Filtro de Mínimos Quadrados Restrito: Utilizado para ajustar um modelo aos dados minimizando a soma dos quadrados das diferenças entre os valores previstos e observados, com restrições adicionais.
Filtro Máximo: Maximiza uma determinada característica, sendo aplicado em diversos contextos, como processamento de imagem e comunicações.
Filtro Mínimo: Minimiza uma característica específica, frequentemente usado em problemas de otimização. Filtro Mediano: Substitui cada pixel em uma imagem pela mediana dos valores dos pixels vizinhos, sendo eficaz para remover ruídos.
Filtro Médio: Calcula a média dos valores em uma região específica, útil para suavizar imagens ou sinais.
Filtro Adaptativo: Ajusta seus parâmetros automaticamente em resposta às características do sinal ou ambiente, proporcionando flexibilidade em várias condições.
Filtro Inverso: Vantagens: Pode oferecer uma compensação precisa. Desvantagens: Sensível a ruídos, instabilidades numéricas.
Filtro Pseudo-Inverso: Vantagens: Útil quando a matriz não é inversível. Desvantagens: A solução é aproximada, não ideal para todos os casos. Filtro de Salsicha: Vantagens: Remove ruídos de alta frequência. Desvantagens: Pode causar suavização excessiva e perda de detalhes.
Filtro de Mínimos Quadrados Restrito: Vantagens: Lida com restrições específicas. Desvantagens: Pode ser sensível a condições iniciais, computacionalmente exigente.
Filtro Máximo: Vantagens: Destaca características específicas. Desvantagens: Pode realçar ruídos indesejados.
Filtro Mínimo: Vantagens: Útil para remoção de ruídos. Desvantagens: Suaviza detalhes importantes.
Filtro Mediano: Vantagens: Eficaz na remoção de ruídos impulsivos. Desvantagens: Pode não ser tão eficaz para outros tipos de ruídos.
Filtro Médio: Vantagens: Suaviza sinais preservando tendências. Desvantagens: Pode não funcionar bem com outliers.
Filtro Adaptativo: Vantagens: Ajusta-se automaticamente a mudanças nas condições. Desvantagens: Complexidade computacional, sensibilidade a condições extremas.
——————————————————————————————————————————————————————————————-
LIMIARIZAÇÃO=
% Carregar a imagem
f = imread(‘football.jpg’); % Substitua ‘football.jpg’ pelo nome da sua imagem
% Converter para escala de cinza
grayImage = rgb2gray(f);
% Definir o limiar
threshold = 0.5; % Pode ser um valor entre 0 e 1, ou um valor específico para imagens em 8 bits (0 a 255)
% Limiarizar a imagem
binaryImage = imbinarize(grayImage, threshold);
% Exibir as imagens
figure;
subplot(1, 2, 1);
imshow(grayImage);
title(‘Imagem em Escala de Cinza’);
subplot(1, 2, 2);
imshow(binaryImage);
title(‘Imagem Limiarizada’);
————————————————————————————————–
ESCALA DE CINZA – BINARIZAÇÃO
f=rgb2gray(imread(‘peppers.png’));
bw=im2bw(f,0.5);
imshow(bw)
m=127;
E=20;
g=1./(1+(m./(double(f)+ eps)).^E)
subplot(1,2,1);imshow(f);subplot(1,2,2);imshow(g);
——————————————————————————————-
AJUSTE DE CONTRASTE
f=rgb2gray(imread(‘peppers.png’));
bw=im2bw(f,0.5);
imshow(bw)
g1= imadjust(f,[0 1],[1 0],0.6);
g2= imadjust(f,[0 1],[1 0],1);
g3= imadjust(f,[0 1],[1 0 ],4);
subplot(1,3,1)
imshow(g1)
subplot(1,3,2)
imshow(g2)
subplot(1,3,3)
imshow(g3)
————————————————————————————————-
imread(‘peppers.png’);
g1= imadjust(f,[0 1],[1 0],0.6);
g2= imadjust(f,[0 1],[1 0],1);
g3= imadjust(f,[0 1],[1 0],4);
subplot(1,3,1)
imshow(g1)
subplot(1,3,2)
imshow(g2)
subplot(1,3,3)
imshow(g3)
——————————————————————————————————————
i=imread(‘peppers.png’);
g=rgb2gray(i);
s=im2uint8(mat2gray(log(1+double(g))));
subplot(1,3,1);imshow(i);subplot(1,3,2);imshow(g);
subplot(1,3,3);imshow(s);
——————————————————————————————————————
f=rgb2gray(imread(‘peppers.png’));
[P, Q]=size(f);
F=fft2(f, 2*P, 2*Q); F=abs(F) ;Fc=fftshift(F);
subplot(1,3,1);imshow(f);subplot(1,3,2);imshow(Fc,[]);
s=im2uint8(mat2gray(log( 1 + double(Fc))));
subplot(1,3,3); imshow(s,[]);
——————————————————————————————————————
fruido=rgb2gray(imread( "boy-6281260_640.jpg"));
w2= (1/64)*ones(8);
g2=im2uint8(mat2gray(imfilter(double(fruido),w2)));
subplot(1,2,1);imshow(fruido);subplot(1,2,2);imshow(g2);
——————————————————————————————————————
A=imread("boy-6281260_640.jpg");
subplot(1,2,1); imshow (A);
k= fspecial(‘average’, [9 9]);
B=imfilter(A, k,"symmetric");
subplot(1,2,2); imshow(B);
————————————————————————————————-
I=rgb2gray(imread(‘boy-6281260_640.jpg’));
subplot(1,3,1), imshow(I);
Isp = imnoise (I, ‘salt & pepper’, 0.03);
subplot(1,3,2), imshow(Isp);
Ig = imnoise (I,’gaussian’, 0.02);
subplot(1,3,3), imshow(Ig);
————————————————————————————————–
I=rgb2gray(imread(‘boy-6281260_640.jpg’));
subplot(1,3,1), imshow(I);
Isp = imnoise (I, ‘salt & pepper’, 0.03);
subplot(1,3,2), imshow(Isp);
Ig = imnoise (I,’gaussian’, 0.02);
subplot(1,3,3), imshow(Ig);
K=ones (3,3)/9;
I_m = imfilter(I,k);
Isp_m = imfilter(Isp,k);
Ig_m = imfilter(Ig,k);
subplot(1,3,1), imshow(I_m);
subplot(1,3,2), imshow(Isp_m);
subplot(1,3,3), imshow(Ig_m);
%%
I_m = medfilt2(I,[3 3]);
Isp_m = medfilt2(Isp,[3 3]);
Ig_m = medfilt2(Ig, [3 3]);
subplot(1,3,1), imshow(I_m);
subplot(1,3,2), imshow(Isp_m);
subplot(1,3,3), imshow(Ig_m);
%%
I_m = ordfilt2(I,25,ones(5,5));
Isp_m = ordfilt2(Isp,25,ones(5,5));
Ig_m = ordfilt2(Ig,25,ones(5,5));
subplot(1,3,1), imshow(I_m);
subplot(1,3,2), imshow(Isp_m);
subplot(1,3,3), imshow(Ig_m);
——————————————————-
Guide —
function varargout = EstudandoThomas(varargin)
gui_Singleton = 1;
gui_State = struct(‘gui_Name’, mfilename, …
‘gui_Singleton’, gui_Singleton, …
‘gui_OpeningFcn’, @EstudandoThomas_OpeningFcn, …
‘gui_OutputFcn’, @EstudandoThomas_OutputFcn, …
‘gui_LayoutFcn’, [] , …
‘gui_Callback’, []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code – DO NOT EDIT
% — Executes just before EstudandoThomas is made visible.
function EstudandoThomas_OpeningFcn(hObject, eventdata, handles, varargin)
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% — Outputs from this function are returned to the command line.
function varargout = EstudandoThomas_OutputFcn(hObject, eventdata, handles)
varargout{1} = handles.output;
% — Executes on button press in Abrir.
function Abrir_Callback(hObject, eventdata, handles)
global im1
[filename,path]=uigetfile(‘*.jpg;*.gif;*.tif;*.png’,’Selecione Imagem’);
im1=imread(strcat(path,filename));
axes(handles.axes1);
imshow(im1);
% — Executes on button press in Cinza.
function Cinza_Callback(hObject, eventdata, handles)
global im1 gray
gray=rgb2gray(im1);
axes(handles.axes2);
imshow(gray);
% — Executes on button press in Histograma.
function Histograma_Callback(hObject, eventdata, handles)
global gray
axes(handles.axes4);
imhist(gray);
% — Executes on button press in Equalizar.
function Equalizar_Callback(hObject, eventdata, handles)
global gray
axes(handles.axes5);
eq=histeq(gray);
imhist(eq);
% — Executes on button press in Salvar.
function Salvar_Callback(hObject, eventdata, handles)
F=getimage(handles.axes3);
FileName=uiputfile({‘*.jpg;*.tif;*.png;*.gif’,’All Image Files’;…
‘*.*’,’All Files’ },’Save Image’,…
‘C:Worknewfile.jpg’)
imwrite(F,FileName,’jpg’);
% — Executes on button press in Reset.
function Reset_Callback(hObject, eventdata, handles)
cla(handles.axes1,’reset’);
cla(handles.axes2,’reset’);
cla(handles.axes3,’reset’);
cla(handles.axes4,’reset’);
cla(handles.axes5,’reset’);
% — Executes on button press in Media.
function Media_Callback(hObject, eventdata, handles)
global gray n
axes(handles.axes3);
w1=(1/(n^2))*ones(n);
g1=im2uint8(mat2gray(imfilter(double(gray),w1)));
imshow(g1);
% — Executes on button press in Mediana.
function Mediana_Callback(hObject, eventdata, handles)
global gray n
axes(handles.axes3);
posicao=double((n^2-1)/2)+1;
g2=ordfilt2(gray,posicao,true(n));
imshow(g2);
% — Executes on button press in Maximo.
function Maximo_Callback(hObject, eventdata, handles)
global gray n
axes(handles.axes3);
g2=ordfilt2(gray,n*n,true(n));
imshow(g2);
% — Executes on button press in Minimo.
function Minimo_Callback(hObject, eventdata, handles)
global gray n
axes(handles.axes3);
g2=ordfilt2(gray,1,true(n));
imshow(g2);
function Matriz_Callback(hObject, eventdata, handles)
global n
str=get(handles.Matriz,’String’);
n=str2double(str);
% — Executes during object creation, after setting all properties.
function Matriz_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,’BackgroundColor’), get(0,’defaultUicontrolBackgroundColor’))
set(hObject,’BackgroundColor’,’white’);
end
% — Executes on button press in Binario.
function Binario_Callback(hObject, eventdata, handles)
global gray
binario=im2bw(gray);
axes(handles.axes3);
imshow(binario)
% — Executes on button press in Negativo.
function Negativo_Callback(hObject, eventdata, handles)
global gray
neg = imadjust(gray, [0 1], [1 0],1);
axes(handles.axes3);
imshow(neg); -Ruído gaussiano: é um tipo de ruído aditivo que segue uma distribuição normal. É comum em imagens capturadas com sensores eletrônicos, como câmeras digitais.
-Ruído sal e pimenta: é um tipo de ruído impulsivo que adiciona pixels brancos ou pretos aleatoriamente na imagem. É comum em imagens capturadas em ambientes com baixa iluminação ou em transmissões de imagens.
– Ruído de Poisson: é um tipo de ruído que ocorre em imagens com baixa intensidade de luz, como imagens médicas ou astronômicas. É causado pela natureza probabilística da captura de fótons.
– Ruído de amplificador: é um tipo de ruído aditivo que ocorre em imagens capturadas com amplificadores eletrônicos, como em câmeras digitais.
– Ruído de tiro: é um tipo de ruído aditivo que ocorre em imagens capturadas com sensores eletrônicos, como câmeras digitais. É causado pela variação aleatória na quantidade de elétrons gerados pelos fotossensores.
– Ruído de quantização: é um tipo de ruído aditivo que ocorre em imagens digitais devido à limitação da resolução do sistema de aquisição de imagens.
– Granulação de filme: é um tipo de ruído aditivo que ocorre em imagens capturadas em filmes fotográficos. É causado pela variação aleatória na densidade de grãos de prata no filme.
– Ruído isotrópico: é um tipo de ruído aditivo que ocorre em imagens digitais devido à variação aleatória na intensidade dos pixels. – Ruído multiplicativo: é um tipo de ruído que ocorre em imagens capturadas por sistemas de radar ou ultrassom. É causado pela reflexão aleatória das ondas sonoras ou eletromagnéticas.
– Ruído periódico: é um tipo de ruído que ocorre em imagens digitais devido à interferência de sinais periódicos, como linhas de energia elétrica ou sinais de televisão.
Filtro de média: é uma técnica de filtragem simples que substitui cada pixel na imagem pela média dos pixels em sua vizinhança. É eficaz para remover ruído gaussiano e ruído de quantização.
Filtro de mediana: é uma técnica de filtragem que substitui cada pixel na imagem pela mediana dos pixels em sua vizinhança. É eficaz para remover ruído impulsivo, como ruído sal e pimenta.
– Filtro de Wiener: é uma técnica de filtragem que usa uma estimativa da densidade espectral de potência do sinal de imagem e do ruído para remover o ruído. É eficaz para remover ruído gaussiano.
Filtro de Kalman: é uma técnica de filtragem que usa um modelo estatístico para estimar o sinal de imagem original a partir do sinal degradado. É eficaz para remover ruído gaussiano e ruído de amplificador.
– Filtro de Anisotrópico: é uma técnica de filtragem que usa uma equação diferencial parcial para remover o ruído enquanto preserva as bordas da imagem. É eficaz para remover ruído gaussiano e ruído de amplificador.
– Filtro de média: – Vantagens: é uma técnica de filtragem simples e fácil de implementar. É eficaz para remover ruído gaussiano e ruído de quantização. – Desvantagens: pode suavizar demais as bordas da imagem e reduzir a nitidez da imagem.
– Filtro de mediana: – Vantagens: é uma técnica de filtragem robusta que é eficaz para remover ruído impulsivo, como ruído sal e pimenta. Preserva as bordas da imagem. – Desvantagens: pode introduzir artefatos na imagem, como halos ao redor das bordas.
– Filtro de Wiener: – Vantagens: é uma técnica de filtragem que usa uma estimativa da densidade espectral de potência do sinal de imagem e do ruído para remover o ruído. É eficaz para remover ruído gaussiano. – Desvantagens: pode introduzir artefatos na imagem, como bordas borradas.
– Filtro de Kalman: – Vantagens: é uma técnica de filtragem que usa um modelo estatístico para estimar o sinal de imagem original a partir do sinal degradado. É eficaz para remover ruído gaussiano e ruído de amplificador. – Desvantagens: é computacionalmente intensivo e pode ser sensível a erros no modelo estatístico.
– Filtro de Anisotrópico: – Vantagens: é uma técnica de filtragem que usa uma equação diferencial parcial para remover o ruído enquanto preserva as bordas da imagem. É eficaz para remover ruído gaussiano e ruído de amplificador. – Desvantagens: é computacionalmente intensivo e pode introduzir artefatos na imagem, como bordas serrilhadas.
Filtro Inverso: Busca compensar ou inverter os efeitos de um sistema, sendo usado em processamento de sinal para melhorar a qualidade. Filtro Pseudo-Inverso: Similar ao inverso, mas aplicado em situações em que a matriz não é diretamente inversível. Usa técnicas alternativas para obter uma solução aproximada.
Filtro de Salsicha: Geralmente referido como filtro passa-baixa, atenua as frequências mais altas em um sinal, destacando as mais baixas. Filtro de Mínimos Quadrados Restrito: Utilizado para ajustar um modelo aos dados minimizando a soma dos quadrados das diferenças entre os valores previstos e observados, com restrições adicionais.
Filtro Máximo: Maximiza uma determinada característica, sendo aplicado em diversos contextos, como processamento de imagem e comunicações.
Filtro Mínimo: Minimiza uma característica específica, frequentemente usado em problemas de otimização. Filtro Mediano: Substitui cada pixel em uma imagem pela mediana dos valores dos pixels vizinhos, sendo eficaz para remover ruídos.
Filtro Médio: Calcula a média dos valores em uma região específica, útil para suavizar imagens ou sinais.
Filtro Adaptativo: Ajusta seus parâmetros automaticamente em resposta às características do sinal ou ambiente, proporcionando flexibilidade em várias condições.
Filtro Inverso: Vantagens: Pode oferecer uma compensação precisa. Desvantagens: Sensível a ruídos, instabilidades numéricas.
Filtro Pseudo-Inverso: Vantagens: Útil quando a matriz não é inversível. Desvantagens: A solução é aproximada, não ideal para todos os casos. Filtro de Salsicha: Vantagens: Remove ruídos de alta frequência. Desvantagens: Pode causar suavização excessiva e perda de detalhes.
Filtro de Mínimos Quadrados Restrito: Vantagens: Lida com restrições específicas. Desvantagens: Pode ser sensível a condições iniciais, computacionalmente exigente.
Filtro Máximo: Vantagens: Destaca características específicas. Desvantagens: Pode realçar ruídos indesejados.
Filtro Mínimo: Vantagens: Útil para remoção de ruídos. Desvantagens: Suaviza detalhes importantes.
Filtro Mediano: Vantagens: Eficaz na remoção de ruídos impulsivos. Desvantagens: Pode não ser tão eficaz para outros tipos de ruídos.
Filtro Médio: Vantagens: Suaviza sinais preservando tendências. Desvantagens: Pode não funcionar bem com outliers.
Filtro Adaptativo: Vantagens: Ajusta-se automaticamente a mudanças nas condições. Desvantagens: Complexidade computacional, sensibilidade a condições extremas.
——————————————————————————————————————————————————————————————-
LIMIARIZAÇÃO=
% Carregar a imagem
f = imread(‘football.jpg’); % Substitua ‘football.jpg’ pelo nome da sua imagem
% Converter para escala de cinza
grayImage = rgb2gray(f);
% Definir o limiar
threshold = 0.5; % Pode ser um valor entre 0 e 1, ou um valor específico para imagens em 8 bits (0 a 255)
% Limiarizar a imagem
binaryImage = imbinarize(grayImage, threshold);
% Exibir as imagens
figure;
subplot(1, 2, 1);
imshow(grayImage);
title(‘Imagem em Escala de Cinza’);
subplot(1, 2, 2);
imshow(binaryImage);
title(‘Imagem Limiarizada’);
————————————————————————————————–
ESCALA DE CINZA – BINARIZAÇÃO
f=rgb2gray(imread(‘peppers.png’));
bw=im2bw(f,0.5);
imshow(bw)
m=127;
E=20;
g=1./(1+(m./(double(f)+ eps)).^E)
subplot(1,2,1);imshow(f);subplot(1,2,2);imshow(g);
——————————————————————————————-
AJUSTE DE CONTRASTE
f=rgb2gray(imread(‘peppers.png’));
bw=im2bw(f,0.5);
imshow(bw)
g1= imadjust(f,[0 1],[1 0],0.6);
g2= imadjust(f,[0 1],[1 0],1);
g3= imadjust(f,[0 1],[1 0 ],4);
subplot(1,3,1)
imshow(g1)
subplot(1,3,2)
imshow(g2)
subplot(1,3,3)
imshow(g3)
————————————————————————————————-
imread(‘peppers.png’);
g1= imadjust(f,[0 1],[1 0],0.6);
g2= imadjust(f,[0 1],[1 0],1);
g3= imadjust(f,[0 1],[1 0],4);
subplot(1,3,1)
imshow(g1)
subplot(1,3,2)
imshow(g2)
subplot(1,3,3)
imshow(g3)
——————————————————————————————————————
i=imread(‘peppers.png’);
g=rgb2gray(i);
s=im2uint8(mat2gray(log(1+double(g))));
subplot(1,3,1);imshow(i);subplot(1,3,2);imshow(g);
subplot(1,3,3);imshow(s);
——————————————————————————————————————
f=rgb2gray(imread(‘peppers.png’));
[P, Q]=size(f);
F=fft2(f, 2*P, 2*Q); F=abs(F) ;Fc=fftshift(F);
subplot(1,3,1);imshow(f);subplot(1,3,2);imshow(Fc,[]);
s=im2uint8(mat2gray(log( 1 + double(Fc))));
subplot(1,3,3); imshow(s,[]);
——————————————————————————————————————
fruido=rgb2gray(imread( "boy-6281260_640.jpg"));
w2= (1/64)*ones(8);
g2=im2uint8(mat2gray(imfilter(double(fruido),w2)));
subplot(1,2,1);imshow(fruido);subplot(1,2,2);imshow(g2);
——————————————————————————————————————
A=imread("boy-6281260_640.jpg");
subplot(1,2,1); imshow (A);
k= fspecial(‘average’, [9 9]);
B=imfilter(A, k,"symmetric");
subplot(1,2,2); imshow(B);
————————————————————————————————-
I=rgb2gray(imread(‘boy-6281260_640.jpg’));
subplot(1,3,1), imshow(I);
Isp = imnoise (I, ‘salt & pepper’, 0.03);
subplot(1,3,2), imshow(Isp);
Ig = imnoise (I,’gaussian’, 0.02);
subplot(1,3,3), imshow(Ig);
————————————————————————————————–
I=rgb2gray(imread(‘boy-6281260_640.jpg’));
subplot(1,3,1), imshow(I);
Isp = imnoise (I, ‘salt & pepper’, 0.03);
subplot(1,3,2), imshow(Isp);
Ig = imnoise (I,’gaussian’, 0.02);
subplot(1,3,3), imshow(Ig);
K=ones (3,3)/9;
I_m = imfilter(I,k);
Isp_m = imfilter(Isp,k);
Ig_m = imfilter(Ig,k);
subplot(1,3,1), imshow(I_m);
subplot(1,3,2), imshow(Isp_m);
subplot(1,3,3), imshow(Ig_m);
%%
I_m = medfilt2(I,[3 3]);
Isp_m = medfilt2(Isp,[3 3]);
Ig_m = medfilt2(Ig, [3 3]);
subplot(1,3,1), imshow(I_m);
subplot(1,3,2), imshow(Isp_m);
subplot(1,3,3), imshow(Ig_m);
%%
I_m = ordfilt2(I,25,ones(5,5));
Isp_m = ordfilt2(Isp,25,ones(5,5));
Ig_m = ordfilt2(Ig,25,ones(5,5));
subplot(1,3,1), imshow(I_m);
subplot(1,3,2), imshow(Isp_m);
subplot(1,3,3), imshow(Ig_m);
——————————————————-
Guide —
function varargout = EstudandoThomas(varargin)
gui_Singleton = 1;
gui_State = struct(‘gui_Name’, mfilename, …
‘gui_Singleton’, gui_Singleton, …
‘gui_OpeningFcn’, @EstudandoThomas_OpeningFcn, …
‘gui_OutputFcn’, @EstudandoThomas_OutputFcn, …
‘gui_LayoutFcn’, [] , …
‘gui_Callback’, []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code – DO NOT EDIT
% — Executes just before EstudandoThomas is made visible.
function EstudandoThomas_OpeningFcn(hObject, eventdata, handles, varargin)
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% — Outputs from this function are returned to the command line.
function varargout = EstudandoThomas_OutputFcn(hObject, eventdata, handles)
varargout{1} = handles.output;
% — Executes on button press in Abrir.
function Abrir_Callback(hObject, eventdata, handles)
global im1
[filename,path]=uigetfile(‘*.jpg;*.gif;*.tif;*.png’,’Selecione Imagem’);
im1=imread(strcat(path,filename));
axes(handles.axes1);
imshow(im1);
% — Executes on button press in Cinza.
function Cinza_Callback(hObject, eventdata, handles)
global im1 gray
gray=rgb2gray(im1);
axes(handles.axes2);
imshow(gray);
% — Executes on button press in Histograma.
function Histograma_Callback(hObject, eventdata, handles)
global gray
axes(handles.axes4);
imhist(gray);
% — Executes on button press in Equalizar.
function Equalizar_Callback(hObject, eventdata, handles)
global gray
axes(handles.axes5);
eq=histeq(gray);
imhist(eq);
% — Executes on button press in Salvar.
function Salvar_Callback(hObject, eventdata, handles)
F=getimage(handles.axes3);
FileName=uiputfile({‘*.jpg;*.tif;*.png;*.gif’,’All Image Files’;…
‘*.*’,’All Files’ },’Save Image’,…
‘C:Worknewfile.jpg’)
imwrite(F,FileName,’jpg’);
% — Executes on button press in Reset.
function Reset_Callback(hObject, eventdata, handles)
cla(handles.axes1,’reset’);
cla(handles.axes2,’reset’);
cla(handles.axes3,’reset’);
cla(handles.axes4,’reset’);
cla(handles.axes5,’reset’);
% — Executes on button press in Media.
function Media_Callback(hObject, eventdata, handles)
global gray n
axes(handles.axes3);
w1=(1/(n^2))*ones(n);
g1=im2uint8(mat2gray(imfilter(double(gray),w1)));
imshow(g1);
% — Executes on button press in Mediana.
function Mediana_Callback(hObject, eventdata, handles)
global gray n
axes(handles.axes3);
posicao=double((n^2-1)/2)+1;
g2=ordfilt2(gray,posicao,true(n));
imshow(g2);
% — Executes on button press in Maximo.
function Maximo_Callback(hObject, eventdata, handles)
global gray n
axes(handles.axes3);
g2=ordfilt2(gray,n*n,true(n));
imshow(g2);
% — Executes on button press in Minimo.
function Minimo_Callback(hObject, eventdata, handles)
global gray n
axes(handles.axes3);
g2=ordfilt2(gray,1,true(n));
imshow(g2);
function Matriz_Callback(hObject, eventdata, handles)
global n
str=get(handles.Matriz,’String’);
n=str2double(str);
% — Executes during object creation, after setting all properties.
function Matriz_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,’BackgroundColor’), get(0,’defaultUicontrolBackgroundColor’))
set(hObject,’BackgroundColor’,’white’);
end
% — Executes on button press in Binario.
function Binario_Callback(hObject, eventdata, handles)
global gray
binario=im2bw(gray);
axes(handles.axes3);
imshow(binario)
% — Executes on button press in Negativo.
function Negativo_Callback(hObject, eventdata, handles)
global gray
neg = imadjust(gray, [0 1], [1 0],1);
axes(handles.axes3);
imshow(neg); filter, ruids MATLAB Answers — New Questions
How can I keep the first two elements from CSV values in a string
I have a Table where one of the columns contains text elements separated by commas. I want to keep the first element (if there is only one) or the first two (if the are more than one). There also could be empty lines. For example, from:
abcd, efgh, tyui
[]
lkjh, poiu
wert
I want to get
abcd, efgh
[]
lkjh, pou
wert
I know how to do this with a for loop. But the idea would be to use regular expressions or something similar to accelerate the process. The Table has almost 2M elements.
Any suggestion would be of great help. Thanks.I have a Table where one of the columns contains text elements separated by commas. I want to keep the first element (if there is only one) or the first two (if the are more than one). There also could be empty lines. For example, from:
abcd, efgh, tyui
[]
lkjh, poiu
wert
I want to get
abcd, efgh
[]
lkjh, pou
wert
I know how to do this with a for loop. But the idea would be to use regular expressions or something similar to accelerate the process. The Table has almost 2M elements.
Any suggestion would be of great help. Thanks. I have a Table where one of the columns contains text elements separated by commas. I want to keep the first element (if there is only one) or the first two (if the are more than one). There also could be empty lines. For example, from:
abcd, efgh, tyui
[]
lkjh, poiu
wert
I want to get
abcd, efgh
[]
lkjh, pou
wert
I know how to do this with a for loop. But the idea would be to use regular expressions or something similar to accelerate the process. The Table has almost 2M elements.
Any suggestion would be of great help. Thanks. regular expressions, text selection MATLAB Answers — New Questions
Bessel function – roots and zeros on interval
Hi, I’m beginner here. I have Bessel function of the first kind J1. I need find roots and zeros on interval <10,20>. Could you help me plase? :/Hi, I’m beginner here. I have Bessel function of the first kind J1. I need find roots and zeros on interval <10,20>. Could you help me plase? :/ Hi, I’m beginner here. I have Bessel function of the first kind J1. I need find roots and zeros on interval <10,20>. Could you help me plase? :/ roots, zeros, bessel function, besselj MATLAB Answers — New Questions
changes the parameters of a fuzzy Inference system in run time
Is this possible to change the parameters of a fuzzy Inference system in runtime? I tried to use some variables of workspace to change the value of membership functions but it give always an error.Is this possible to change the parameters of a fuzzy Inference system in runtime? I tried to use some variables of workspace to change the value of membership functions but it give always an error. Is this possible to change the parameters of a fuzzy Inference system in runtime? I tried to use some variables of workspace to change the value of membership functions but it give always an error. transferred MATLAB Answers — New Questions
How to address this issue and enhance pixel quality by estimating or predicting the missing (zero) pixels, by using AI models
Post Content Post Content ai, deep learning, image analysis, image processing, video processing, video, pixles, digital image processing MATLAB Answers — New Questions
Adsorption process in Simulink
How to create a switch command between adsorption and desorption in Simulink?How to create a switch command between adsorption and desorption in Simulink? How to create a switch command between adsorption and desorption in Simulink? adsorption, simulink, switch command MATLAB Answers — New Questions
How to apply a legend to a graphed model array?
Hello, I have a created a model array of transfer functions using stack() and they are labeled with their varying parameters using SamplingGrid.
Yarray = feedback(Garray,1);
Yarray.SamplingGrid = struct(‘zeta’,dr);
figure;
set(gcf,’Visible’,’on’)
step(Yarray, 60)
How do I apply a visible legend to this graph? I like the normal legend() function that applies the titles and automatically changes the colors. However, calling this function either with my desired labels or empty just has the default color line labeled as ‘Yarray.’ I would love if they could be labeled dynamically following the SamplingGrid structure.Hello, I have a created a model array of transfer functions using stack() and they are labeled with their varying parameters using SamplingGrid.
Yarray = feedback(Garray,1);
Yarray.SamplingGrid = struct(‘zeta’,dr);
figure;
set(gcf,’Visible’,’on’)
step(Yarray, 60)
How do I apply a visible legend to this graph? I like the normal legend() function that applies the titles and automatically changes the colors. However, calling this function either with my desired labels or empty just has the default color line labeled as ‘Yarray.’ I would love if they could be labeled dynamically following the SamplingGrid structure. Hello, I have a created a model array of transfer functions using stack() and they are labeled with their varying parameters using SamplingGrid.
Yarray = feedback(Garray,1);
Yarray.SamplingGrid = struct(‘zeta’,dr);
figure;
set(gcf,’Visible’,’on’)
step(Yarray, 60)
How do I apply a visible legend to this graph? I like the normal legend() function that applies the titles and automatically changes the colors. However, calling this function either with my desired labels or empty just has the default color line labeled as ‘Yarray.’ I would love if they could be labeled dynamically following the SamplingGrid structure. model array, legend, step MATLAB Answers — New Questions
How to draw isolines between points?
Hello everyone!
I have points with known geographic coordinates and certain values. How do I draw isolines (lines of equal values) or a continuous color field between them on the map?Hello everyone!
I have points with known geographic coordinates and certain values. How do I draw isolines (lines of equal values) or a continuous color field between them on the map? Hello everyone!
I have points with known geographic coordinates and certain values. How do I draw isolines (lines of equal values) or a continuous color field between them on the map? map, isolines, contour MATLAB Answers — New Questions
Why is my modified path not saved in MATLAB?
I am modifying my MATLAB path by using either the "Set Path" button in the toolbar, or by using the "addpath" and "savepath" commands in the MATLAB Command Window. However, when I exit MATLAB and restart it, the MATLAB search path does not reflect the changes that I had made.
Why are my MATLAB path modifications not saved in the new session of MATLAB?I am modifying my MATLAB path by using either the "Set Path" button in the toolbar, or by using the "addpath" and "savepath" commands in the MATLAB Command Window. However, when I exit MATLAB and restart it, the MATLAB search path does not reflect the changes that I had made.
Why are my MATLAB path modifications not saved in the new session of MATLAB? I am modifying my MATLAB path by using either the "Set Path" button in the toolbar, or by using the "addpath" and "savepath" commands in the MATLAB Command Window. However, when I exit MATLAB and restart it, the MATLAB search path does not reflect the changes that I had made.
Why are my MATLAB path modifications not saved in the new session of MATLAB? addpath, savepath MATLAB Answers — New Questions
compute rotation angle of binary shape image without having primary image(image before rotation)
I have some binary image of letters.I need to rotate these letters shapes X degree, then compute the degree of rotation (X) without having the first letters shapes image (Not-Rotated shapes).
I tested several ways. I used RegionProps.Rotation(RP.R), but had little accuracy.
For example if RP.R is 90 degree, after 5 degree rotation with imrotate method, it will be 80 degree instead 85 degree.
Also I used minimum bounding box;before and after rotating the shapes, I measure the angle between square diagonal and x-axis, or on side of square and x-axis. In this way,for some shapes of letters, measure specified angle after rotating the shape and it was inaccurate and in some cases after X degree rotation(X = 2,3, or 5 degree),the specified angle was unchanged (figure1).
<</matlabcentral/answers/uploaded_files/106773/Figure2.png>>
I want to familiar me with a solution for this problem with these constraints:
-we don’t have the ascii code.
-we couldn’t used OCR for letter detection
-for angle calculation,we don’t have the primary image shape.
thank you.I have some binary image of letters.I need to rotate these letters shapes X degree, then compute the degree of rotation (X) without having the first letters shapes image (Not-Rotated shapes).
I tested several ways. I used RegionProps.Rotation(RP.R), but had little accuracy.
For example if RP.R is 90 degree, after 5 degree rotation with imrotate method, it will be 80 degree instead 85 degree.
Also I used minimum bounding box;before and after rotating the shapes, I measure the angle between square diagonal and x-axis, or on side of square and x-axis. In this way,for some shapes of letters, measure specified angle after rotating the shape and it was inaccurate and in some cases after X degree rotation(X = 2,3, or 5 degree),the specified angle was unchanged (figure1).
<</matlabcentral/answers/uploaded_files/106773/Figure2.png>>
I want to familiar me with a solution for this problem with these constraints:
-we don’t have the ascii code.
-we couldn’t used OCR for letter detection
-for angle calculation,we don’t have the primary image shape.
thank you. I have some binary image of letters.I need to rotate these letters shapes X degree, then compute the degree of rotation (X) without having the first letters shapes image (Not-Rotated shapes).
I tested several ways. I used RegionProps.Rotation(RP.R), but had little accuracy.
For example if RP.R is 90 degree, after 5 degree rotation with imrotate method, it will be 80 degree instead 85 degree.
Also I used minimum bounding box;before and after rotating the shapes, I measure the angle between square diagonal and x-axis, or on side of square and x-axis. In this way,for some shapes of letters, measure specified angle after rotating the shape and it was inaccurate and in some cases after X degree rotation(X = 2,3, or 5 degree),the specified angle was unchanged (figure1).
<</matlabcentral/answers/uploaded_files/106773/Figure2.png>>
I want to familiar me with a solution for this problem with these constraints:
-we don’t have the ascii code.
-we couldn’t used OCR for letter detection
-for angle calculation,we don’t have the primary image shape.
thank you. text image processing, text image rotation, image processing MATLAB Answers — New Questions
Help with time variation graphs versus time
Hi everyone.
Can you help me on how I can obtain this type of graphs (see example), which represent amplitude variations at a certain frequency with respect to time. Note that the Y axis is in logarithmic. A small sample of my data is:
Date time Freq Amplitude
2010/01/01 00:00 0.109864 2.04021
2010/01/01 00:00 0.122071 2.8937
2010/01/01 00:00 0.134278 2.84502
2010/01/01 00:00 0.146485 2.92267
2010/01/01 00:00 0.158692 3.11156
2010/01/01 00:00 0.170899 3.41533
2010/01/01 00:00 0.183107 3.10193
2010/01/01 00:00 0.195314 3.32969
2010/01/01 00:00 0.207521 3.29483
2010/01/01 00:00 0.219728 3.21573
Thank to allHi everyone.
Can you help me on how I can obtain this type of graphs (see example), which represent amplitude variations at a certain frequency with respect to time. Note that the Y axis is in logarithmic. A small sample of my data is:
Date time Freq Amplitude
2010/01/01 00:00 0.109864 2.04021
2010/01/01 00:00 0.122071 2.8937
2010/01/01 00:00 0.134278 2.84502
2010/01/01 00:00 0.146485 2.92267
2010/01/01 00:00 0.158692 3.11156
2010/01/01 00:00 0.170899 3.41533
2010/01/01 00:00 0.183107 3.10193
2010/01/01 00:00 0.195314 3.32969
2010/01/01 00:00 0.207521 3.29483
2010/01/01 00:00 0.219728 3.21573
Thank to all Hi everyone.
Can you help me on how I can obtain this type of graphs (see example), which represent amplitude variations at a certain frequency with respect to time. Note that the Y axis is in logarithmic. A small sample of my data is:
Date time Freq Amplitude
2010/01/01 00:00 0.109864 2.04021
2010/01/01 00:00 0.122071 2.8937
2010/01/01 00:00 0.134278 2.84502
2010/01/01 00:00 0.146485 2.92267
2010/01/01 00:00 0.158692 3.11156
2010/01/01 00:00 0.170899 3.41533
2010/01/01 00:00 0.183107 3.10193
2010/01/01 00:00 0.195314 3.32969
2010/01/01 00:00 0.207521 3.29483
2010/01/01 00:00 0.219728 3.21573
Thank to all spectrogram, hvgram, temporal variations MATLAB Answers — New Questions
Gradient Descent optimization in an electrical circuit or transmission line
Is there any sample work of gradient descent based optimization of an electrical circuit or transmission line parameters done using MATLAB? I am trying to optimize the parameters of a nonlinear transmission line using gradient descent algorithm. I intend to use Matlab and LTspice. Any help regarding this problem would be greatly appreciated. Thanks.Is there any sample work of gradient descent based optimization of an electrical circuit or transmission line parameters done using MATLAB? I am trying to optimize the parameters of a nonlinear transmission line using gradient descent algorithm. I intend to use Matlab and LTspice. Any help regarding this problem would be greatly appreciated. Thanks. Is there any sample work of gradient descent based optimization of an electrical circuit or transmission line parameters done using MATLAB? I am trying to optimize the parameters of a nonlinear transmission line using gradient descent algorithm. I intend to use Matlab and LTspice. Any help regarding this problem would be greatly appreciated. Thanks. gradient descent, optimization, circuits, transmission line, matlab, ltspice, ads MATLAB Answers — New Questions
propagateOrbit function hangs for no obvious reason
When the propagateOrbit function is fed certain TLEs, it simply stalls instead of throwing an exception. Since the propagateOrbit function is compiled, there is no way to trace and debug the hangup. When I press the "Pause" button, it greys out and says "pausing". If I press "Stop", I get the following message:
Operation terminated by user during matlabshared.orbit.internal.SGP4.propagate
For example, this TLE appears to be toxic:
1 52643U 00000A 22181.91667824 -.00046528 00000-0 32759-0 0 10
2 52643 53.2133 206.5805 0002347 15.7379 205.9837 15.73290591 1300
Here is a code example:
formatTime = ‘uuuu:DDD:HH:mm:ss.SSS’;
start_time = 2022:182:11:08:05.800′;
dt_start_time = datetime(start_time,’InputFormat’, formatTime);
tlestruct = tleread(‘tle_52643.tle’);
[r,v] = propagateOrbit(dt_start_time, tlestruct);
In some cases, propagateOrbit() is unable to resolve an orbit. This is to be expected; however, instead of throwing an exception, the function outputs a set of matrices containing complex numbers.If you then try to do a coordinate transformation on the r and v matrices using eci2ecef(), the code blows up.
Here is an example of a satellite TLE that does not resolve:
1 87954U 00000A 11327.05272112 .00003699 00000-0 57015-0 0 10
2 87954 98.4963 251.3127 0116186 87.4088 331.4134 14.69587133 3680
[r,v] = propagateOrbit(dt_start_time, tlestruct);
r = 1.0e+24 *
-1.2748 – 3.5603i
-4.3786 – 5.0800i
7.0058 – 3.8228i
On a related note, the tleread function will fail if the BSTAR term’s minus sign is not exactly in column 54. If the BSTAR mantissa is less than five digits long and the minus sign gets displaced to the right, tleread() is unable to generate a TLE. Some sites like Celestrak are more diligent about adding leading zeros to the BSTAR term, but others are not and can lead you to trouble.
SUGGESTION: Make tleread() more user-friendly?When the propagateOrbit function is fed certain TLEs, it simply stalls instead of throwing an exception. Since the propagateOrbit function is compiled, there is no way to trace and debug the hangup. When I press the "Pause" button, it greys out and says "pausing". If I press "Stop", I get the following message:
Operation terminated by user during matlabshared.orbit.internal.SGP4.propagate
For example, this TLE appears to be toxic:
1 52643U 00000A 22181.91667824 -.00046528 00000-0 32759-0 0 10
2 52643 53.2133 206.5805 0002347 15.7379 205.9837 15.73290591 1300
Here is a code example:
formatTime = ‘uuuu:DDD:HH:mm:ss.SSS’;
start_time = 2022:182:11:08:05.800′;
dt_start_time = datetime(start_time,’InputFormat’, formatTime);
tlestruct = tleread(‘tle_52643.tle’);
[r,v] = propagateOrbit(dt_start_time, tlestruct);
In some cases, propagateOrbit() is unable to resolve an orbit. This is to be expected; however, instead of throwing an exception, the function outputs a set of matrices containing complex numbers.If you then try to do a coordinate transformation on the r and v matrices using eci2ecef(), the code blows up.
Here is an example of a satellite TLE that does not resolve:
1 87954U 00000A 11327.05272112 .00003699 00000-0 57015-0 0 10
2 87954 98.4963 251.3127 0116186 87.4088 331.4134 14.69587133 3680
[r,v] = propagateOrbit(dt_start_time, tlestruct);
r = 1.0e+24 *
-1.2748 – 3.5603i
-4.3786 – 5.0800i
7.0058 – 3.8228i
On a related note, the tleread function will fail if the BSTAR term’s minus sign is not exactly in column 54. If the BSTAR mantissa is less than five digits long and the minus sign gets displaced to the right, tleread() is unable to generate a TLE. Some sites like Celestrak are more diligent about adding leading zeros to the BSTAR term, but others are not and can lead you to trouble.
SUGGESTION: Make tleread() more user-friendly? When the propagateOrbit function is fed certain TLEs, it simply stalls instead of throwing an exception. Since the propagateOrbit function is compiled, there is no way to trace and debug the hangup. When I press the "Pause" button, it greys out and says "pausing". If I press "Stop", I get the following message:
Operation terminated by user during matlabshared.orbit.internal.SGP4.propagate
For example, this TLE appears to be toxic:
1 52643U 00000A 22181.91667824 -.00046528 00000-0 32759-0 0 10
2 52643 53.2133 206.5805 0002347 15.7379 205.9837 15.73290591 1300
Here is a code example:
formatTime = ‘uuuu:DDD:HH:mm:ss.SSS’;
start_time = 2022:182:11:08:05.800′;
dt_start_time = datetime(start_time,’InputFormat’, formatTime);
tlestruct = tleread(‘tle_52643.tle’);
[r,v] = propagateOrbit(dt_start_time, tlestruct);
In some cases, propagateOrbit() is unable to resolve an orbit. This is to be expected; however, instead of throwing an exception, the function outputs a set of matrices containing complex numbers.If you then try to do a coordinate transformation on the r and v matrices using eci2ecef(), the code blows up.
Here is an example of a satellite TLE that does not resolve:
1 87954U 00000A 11327.05272112 .00003699 00000-0 57015-0 0 10
2 87954 98.4963 251.3127 0116186 87.4088 331.4134 14.69587133 3680
[r,v] = propagateOrbit(dt_start_time, tlestruct);
r = 1.0e+24 *
-1.2748 – 3.5603i
-4.3786 – 5.0800i
7.0058 – 3.8228i
On a related note, the tleread function will fail if the BSTAR term’s minus sign is not exactly in column 54. If the BSTAR mantissa is less than five digits long and the minus sign gets displaced to the right, tleread() is unable to generate a TLE. Some sites like Celestrak are more diligent about adding leading zeros to the BSTAR term, but others are not and can lead you to trouble.
SUGGESTION: Make tleread() more user-friendly? tle, propagateorbit, two-line elements MATLAB Answers — New Questions
Built in function cd not being found when running a custom function
Hello, I am having an issue where cd is not being found when I run a custom script. The relevant script is as follows, [tmp] being a placeholder that removes identifying information. cvfn is the name of a file that is located in basepath.
function horm_symptom(cvfn)
close all;
basepath={‘C:\Users\[tmp]_WorkingFolder’;
‘C:\Users\[tmp]_WorkingFolder’};
if exist(basepath{1},’dir’), basepath=basepath{1};
elseif exist(basepath{2},’dir’), basepath=basepath{2};
else, error(‘basepath does not exist’);
end
addpath(genpath(basepath));
savepath=fullfile(basepath,’SingleSubjectData’);
if ~exist(savepath,’dir’), mkdir(savepath); end
cd(‘SingleSubjectData’);
When i run the script I get the following error at the line cd(‘SingleSubjectData’)
Unrecognized function or variable ‘cd’.
However, if I set a breakpoint at ‘cd(‘SingleSubjectData’);’ and type the following, I get:
exist(‘cd’,’builtin’)
ans =
5
which(‘cd’)
ans =
built-in (C:Program FilesMATLABR2023btoolboxmatlabgeneralcd)
I’ve also successfully used addpath to the above directory with no errors, but even still I get the unrecognized function error.
addpath(‘C:Program FilesMATLABR2023btoolboxmatlabgeneral’)
I’ve tried different formats for cd, including adding and removing parentheses, semi-colons, and tildes and nothing has worked.
If I set a break point and type the following directly into the command window it works and changes directory,
cd ‘SingleSubjectData’
However, if I try to run the code with the above formatting within the script I get the following error:
horm_symptom(cvfn)
Error: File: horm_symptom.m Line: 21 Column: 1
Using identifier ‘cd’ as both a variable and a command is not supported. For more information, see "How MATLAB
Recognizes Command Syntax".
The above error occurs when I try any of the following formats:
cd SingleSubjectData;
cd SingleSubjectData
cd ‘SingleSubjectData’
cd ‘SingleSubjectData’;
cd ~/SingleSubjectData
I have checked that a variable named "cd" is not getting created, confirmed that the sub folder SingleSubjectData is getting created and does exist and reviewed the How Matlab recognizes command syntax page linked in the error. I am at a loss of how to fix this or whats wrong. Lastly, I know I’m talking about SingleSubjectData, but I have also tried cding into savepath, and have had all the same errors described above. Please help!Hello, I am having an issue where cd is not being found when I run a custom script. The relevant script is as follows, [tmp] being a placeholder that removes identifying information. cvfn is the name of a file that is located in basepath.
function horm_symptom(cvfn)
close all;
basepath={‘C:\Users\[tmp]_WorkingFolder’;
‘C:\Users\[tmp]_WorkingFolder’};
if exist(basepath{1},’dir’), basepath=basepath{1};
elseif exist(basepath{2},’dir’), basepath=basepath{2};
else, error(‘basepath does not exist’);
end
addpath(genpath(basepath));
savepath=fullfile(basepath,’SingleSubjectData’);
if ~exist(savepath,’dir’), mkdir(savepath); end
cd(‘SingleSubjectData’);
When i run the script I get the following error at the line cd(‘SingleSubjectData’)
Unrecognized function or variable ‘cd’.
However, if I set a breakpoint at ‘cd(‘SingleSubjectData’);’ and type the following, I get:
exist(‘cd’,’builtin’)
ans =
5
which(‘cd’)
ans =
built-in (C:Program FilesMATLABR2023btoolboxmatlabgeneralcd)
I’ve also successfully used addpath to the above directory with no errors, but even still I get the unrecognized function error.
addpath(‘C:Program FilesMATLABR2023btoolboxmatlabgeneral’)
I’ve tried different formats for cd, including adding and removing parentheses, semi-colons, and tildes and nothing has worked.
If I set a break point and type the following directly into the command window it works and changes directory,
cd ‘SingleSubjectData’
However, if I try to run the code with the above formatting within the script I get the following error:
horm_symptom(cvfn)
Error: File: horm_symptom.m Line: 21 Column: 1
Using identifier ‘cd’ as both a variable and a command is not supported. For more information, see "How MATLAB
Recognizes Command Syntax".
The above error occurs when I try any of the following formats:
cd SingleSubjectData;
cd SingleSubjectData
cd ‘SingleSubjectData’
cd ‘SingleSubjectData’;
cd ~/SingleSubjectData
I have checked that a variable named "cd" is not getting created, confirmed that the sub folder SingleSubjectData is getting created and does exist and reviewed the How Matlab recognizes command syntax page linked in the error. I am at a loss of how to fix this or whats wrong. Lastly, I know I’m talking about SingleSubjectData, but I have also tried cding into savepath, and have had all the same errors described above. Please help! Hello, I am having an issue where cd is not being found when I run a custom script. The relevant script is as follows, [tmp] being a placeholder that removes identifying information. cvfn is the name of a file that is located in basepath.
function horm_symptom(cvfn)
close all;
basepath={‘C:\Users\[tmp]_WorkingFolder’;
‘C:\Users\[tmp]_WorkingFolder’};
if exist(basepath{1},’dir’), basepath=basepath{1};
elseif exist(basepath{2},’dir’), basepath=basepath{2};
else, error(‘basepath does not exist’);
end
addpath(genpath(basepath));
savepath=fullfile(basepath,’SingleSubjectData’);
if ~exist(savepath,’dir’), mkdir(savepath); end
cd(‘SingleSubjectData’);
When i run the script I get the following error at the line cd(‘SingleSubjectData’)
Unrecognized function or variable ‘cd’.
However, if I set a breakpoint at ‘cd(‘SingleSubjectData’);’ and type the following, I get:
exist(‘cd’,’builtin’)
ans =
5
which(‘cd’)
ans =
built-in (C:Program FilesMATLABR2023btoolboxmatlabgeneralcd)
I’ve also successfully used addpath to the above directory with no errors, but even still I get the unrecognized function error.
addpath(‘C:Program FilesMATLABR2023btoolboxmatlabgeneral’)
I’ve tried different formats for cd, including adding and removing parentheses, semi-colons, and tildes and nothing has worked.
If I set a break point and type the following directly into the command window it works and changes directory,
cd ‘SingleSubjectData’
However, if I try to run the code with the above formatting within the script I get the following error:
horm_symptom(cvfn)
Error: File: horm_symptom.m Line: 21 Column: 1
Using identifier ‘cd’ as both a variable and a command is not supported. For more information, see "How MATLAB
Recognizes Command Syntax".
The above error occurs when I try any of the following formats:
cd SingleSubjectData;
cd SingleSubjectData
cd ‘SingleSubjectData’
cd ‘SingleSubjectData’;
cd ~/SingleSubjectData
I have checked that a variable named "cd" is not getting created, confirmed that the sub folder SingleSubjectData is getting created and does exist and reviewed the How Matlab recognizes command syntax page linked in the error. I am at a loss of how to fix this or whats wrong. Lastly, I know I’m talking about SingleSubjectData, but I have also tried cding into savepath, and have had all the same errors described above. Please help! error, built in function MATLAB Answers — New Questions
What filtration should be used for a respiratory signal between 5 and 60 breaths per minute?
I have applied LPF and HPF filtering, but for a low-frequency respiratory signal, the signal after HPF is distorted and edge detection is incorrect, as can be seen in the attached photo. Is it possible to use some kind of filtration that can handle the respiratory signal range of 5-60 breaths per minute? Is it better to use a findpeaks function with appropriate limitations and only LPF filtering as in diagram 2 in the attached photo?
% ————- LPF ——————————
N = 5; % Order
Fstop = 1.4; % Stopband Frequency
Astop = 30; % Stopband Attenuation (dB)
Fs = 25; % Sampling Frequency
h = fdesign.lowpass(‘n,fst,ast’, N, Fstop, Astop, Fs);
hfiltLP = design(h, ‘cheby2’, ‘SystemObject’, true);
% ————- HPF ——————————
N = 4; % Order
Fstop = 4/60; % Stopband Frequency min 4 oddechow na minute
Astop = 60; % Stopband Attenuation (dB)
Fs = 25; % Sampling Frequency
h = fdesign.highpass(‘n,fst,ast’, N, Fstop, Astop, Fs);
hfiltHP = design(h, ‘cheby2’, ‘SystemObject’, true);I have applied LPF and HPF filtering, but for a low-frequency respiratory signal, the signal after HPF is distorted and edge detection is incorrect, as can be seen in the attached photo. Is it possible to use some kind of filtration that can handle the respiratory signal range of 5-60 breaths per minute? Is it better to use a findpeaks function with appropriate limitations and only LPF filtering as in diagram 2 in the attached photo?
% ————- LPF ——————————
N = 5; % Order
Fstop = 1.4; % Stopband Frequency
Astop = 30; % Stopband Attenuation (dB)
Fs = 25; % Sampling Frequency
h = fdesign.lowpass(‘n,fst,ast’, N, Fstop, Astop, Fs);
hfiltLP = design(h, ‘cheby2’, ‘SystemObject’, true);
% ————- HPF ——————————
N = 4; % Order
Fstop = 4/60; % Stopband Frequency min 4 oddechow na minute
Astop = 60; % Stopband Attenuation (dB)
Fs = 25; % Sampling Frequency
h = fdesign.highpass(‘n,fst,ast’, N, Fstop, Astop, Fs);
hfiltHP = design(h, ‘cheby2’, ‘SystemObject’, true); I have applied LPF and HPF filtering, but for a low-frequency respiratory signal, the signal after HPF is distorted and edge detection is incorrect, as can be seen in the attached photo. Is it possible to use some kind of filtration that can handle the respiratory signal range of 5-60 breaths per minute? Is it better to use a findpeaks function with appropriate limitations and only LPF filtering as in diagram 2 in the attached photo?
% ————- LPF ——————————
N = 5; % Order
Fstop = 1.4; % Stopband Frequency
Astop = 30; % Stopband Attenuation (dB)
Fs = 25; % Sampling Frequency
h = fdesign.lowpass(‘n,fst,ast’, N, Fstop, Astop, Fs);
hfiltLP = design(h, ‘cheby2’, ‘SystemObject’, true);
% ————- HPF ——————————
N = 4; % Order
Fstop = 4/60; % Stopband Frequency min 4 oddechow na minute
Astop = 60; % Stopband Attenuation (dB)
Fs = 25; % Sampling Frequency
h = fdesign.highpass(‘n,fst,ast’, N, Fstop, Astop, Fs);
hfiltHP = design(h, ‘cheby2’, ‘SystemObject’, true); respiratory rate, respiration, filtering MATLAB Answers — New Questions
How to get the answer from the following code. How can i extract the values from the code?
%I have the following non-linear coupled ODE’S
%u"+(Nt*G1*u’)+(M1*G2*h’)+(R1*u)+(G3*GT*Theta)+(G4*GC*Phi)=0,
%(1+iHc)*G5*h"+u’+Nt*Pm*h’=0,
%T"+(Nt*Pr*G6)*T’-(S1*Pr*G7*T)=0;
%C"+(Nt*Sc*G8*C’)-(Hp*Sc*G8*C)=0;
% Boundary conditions: u=1, h=1,T’=G7*B1*(T-1),C’=G8*F1*(C-1) at y=0.
% u’,h’,T,C = 0 at y tends to infinity.
clc
B1 = 0.5;
F1 = 0.5;
k = 0.3;
RO = 0.5;
Hp = 0.2;
M1 = 16;
Nt = 0.15;
Pr = 6.2;
Pm = 0.7;
S1 = 1;
P1 = 0.02;
P2 = 0.0;
Sc = 0.78;
Hc = 0.5;
GT = 4;
GC = 5;
e1 = (1./(((1-P1).^2.5).*((1-P2).^2.5)));
Ros1 = 4420;
Ros2 = 5180;
Rof = 997.1;
Ro1 = (Ros1./Rof);
Ro2 = (Ros2./Rof);
e2 = ((1-P2).*((1-P1)+(P1.*Ro1)))+(P2.*Ro2);
Betas1 = 0.000058;
Betas2 = 0.000013;
Betaf = 0.00021;
Beta1 = ((Ros1.*Betas1)./(Rof.*Betaf));
Beta2 = ((Ros2.*Betas2)./(Rof.*Betaf));
e3 = ((1-P2).*((1-P1)+(P1.*Beta1)))+(P2.*Beta2);
BetaCs1 = 0.006;
BetaCs2 = 0.45;
BetaCf = 1;
BetaC1 = ((Ros1.*BetaCs1)./(Rof.*BetaCf));
BetaC2 = ((Ros2.*BetaCs2)./(Rof.*BetaCf));
e4 = ((1-P2).*((1-P1)+(P1.*BetaC1)))+(P2.*BetaC2);
sigmas1 = 580000;
sigmas2 = 25000;
sigmaf = 0.005;
sigma = (sigmas1./sigmaf);
d5 = (((1+2.*P1)+(2.*(1-P1).*(1./sigma)))./((1-P1)+((2+P1).*(1./sigma))));
e5 = d5.*(((sigmas2.*(1+2.*P2))+(2.*d5.*sigmaf.*(1-P2)))./((sigmas2.*(1-P2))+(d5.*sigmaf.*(2+P2))));
Cps1 = 0.56;
Cps2 = 670;
Cpf = 4179;
RoCp1 = ((Ros1.*Cps1)./(Rof.*Cpf));
RoCp2 = ((Ros2.*Cps2)./(Rof.*Cpf));
e6 = ((1-P2).*((1-P1)+(P1.*RoCp1)))+(P2.*RoCp2);
Ks1 = 7.2;
Ks2 = 9.7;
Kf = 0.613;
K = (Kf./Ks1);
d7 = (((1+2.*P1)+(2.*(1-P1).*K))./((1-P1)+((2+P1).*K)));
e7 = d7*((((Ks2+2.*d7.*Kf)+(2.*d7.*Kf))+(2.*P2.*(Ks2-d7.*Kf)))./((Ks2+2.*d7.*Kf)-(P2.*(Ks2-d7.*Kf))));
e8 = ((1-P1).*(1-P2));
G1 = (e2./e1);
G2 = (1./e1);
G3 = (e3./e1);
G4 = (e4./e1);
G5 = (1./e5);
G6 = (e6./e7);
G7 = (1./e7);
G8 = (1./e8);
dydx = @(x,y)[y(5);
y(6);
y(7);
y(8);
-(Nt.*Pr.*G6.*y(5))+(S1.*Pr.*G6.*y(1));
-(Nt.*Sc.*G8.*y(6))+(Hp.*Sc.*G8.*y(2));
-(Nt.*G1.*y(7))-(M1.*G2.*y(8))-(((2.*1i.*RO.*G1)-(1./k)).*y(3))-(GT.*G3.*y(1))-(GC.*G4.*y(2));
-((y(7)./((1+1i.*Hc).*G5)))-((Nt.*Pm.*y(8))./((1+1i.*Hc).*G5))];
BC1 = @(ya,yb)[(ya(5)-G7.*B1.*(ya(1)-1));yb(1);
(ya(6)-G8.*F1.*(ya(2)-1));yb(2);
ya(3)-1;yb(7);
ya(4)-1;yb(8)];
yinit = [0.1;0.1;0.1;0.1;0.1;0.1;0.1;0.1];
solinit = bvpinit(linspace(0,2,50),yinit);
options = bvpset(‘AbsTol’,1e-3,’RelTol’,1e-3,’stats’,’off’,’Nmax’,1000);
U1 = bvp4c(dydx,BC1,solinit,options);
I need to find the following
F = ((du/dy)-Nt*(d^2u/dy^2)) at y=0,J = -(i*(dh/dy)) at y=0,
N1 = -(dT/dy) at y=0, N2 = -(dC/dy) at y=0.%I have the following non-linear coupled ODE’S
%u"+(Nt*G1*u’)+(M1*G2*h’)+(R1*u)+(G3*GT*Theta)+(G4*GC*Phi)=0,
%(1+iHc)*G5*h"+u’+Nt*Pm*h’=0,
%T"+(Nt*Pr*G6)*T’-(S1*Pr*G7*T)=0;
%C"+(Nt*Sc*G8*C’)-(Hp*Sc*G8*C)=0;
% Boundary conditions: u=1, h=1,T’=G7*B1*(T-1),C’=G8*F1*(C-1) at y=0.
% u’,h’,T,C = 0 at y tends to infinity.
clc
B1 = 0.5;
F1 = 0.5;
k = 0.3;
RO = 0.5;
Hp = 0.2;
M1 = 16;
Nt = 0.15;
Pr = 6.2;
Pm = 0.7;
S1 = 1;
P1 = 0.02;
P2 = 0.0;
Sc = 0.78;
Hc = 0.5;
GT = 4;
GC = 5;
e1 = (1./(((1-P1).^2.5).*((1-P2).^2.5)));
Ros1 = 4420;
Ros2 = 5180;
Rof = 997.1;
Ro1 = (Ros1./Rof);
Ro2 = (Ros2./Rof);
e2 = ((1-P2).*((1-P1)+(P1.*Ro1)))+(P2.*Ro2);
Betas1 = 0.000058;
Betas2 = 0.000013;
Betaf = 0.00021;
Beta1 = ((Ros1.*Betas1)./(Rof.*Betaf));
Beta2 = ((Ros2.*Betas2)./(Rof.*Betaf));
e3 = ((1-P2).*((1-P1)+(P1.*Beta1)))+(P2.*Beta2);
BetaCs1 = 0.006;
BetaCs2 = 0.45;
BetaCf = 1;
BetaC1 = ((Ros1.*BetaCs1)./(Rof.*BetaCf));
BetaC2 = ((Ros2.*BetaCs2)./(Rof.*BetaCf));
e4 = ((1-P2).*((1-P1)+(P1.*BetaC1)))+(P2.*BetaC2);
sigmas1 = 580000;
sigmas2 = 25000;
sigmaf = 0.005;
sigma = (sigmas1./sigmaf);
d5 = (((1+2.*P1)+(2.*(1-P1).*(1./sigma)))./((1-P1)+((2+P1).*(1./sigma))));
e5 = d5.*(((sigmas2.*(1+2.*P2))+(2.*d5.*sigmaf.*(1-P2)))./((sigmas2.*(1-P2))+(d5.*sigmaf.*(2+P2))));
Cps1 = 0.56;
Cps2 = 670;
Cpf = 4179;
RoCp1 = ((Ros1.*Cps1)./(Rof.*Cpf));
RoCp2 = ((Ros2.*Cps2)./(Rof.*Cpf));
e6 = ((1-P2).*((1-P1)+(P1.*RoCp1)))+(P2.*RoCp2);
Ks1 = 7.2;
Ks2 = 9.7;
Kf = 0.613;
K = (Kf./Ks1);
d7 = (((1+2.*P1)+(2.*(1-P1).*K))./((1-P1)+((2+P1).*K)));
e7 = d7*((((Ks2+2.*d7.*Kf)+(2.*d7.*Kf))+(2.*P2.*(Ks2-d7.*Kf)))./((Ks2+2.*d7.*Kf)-(P2.*(Ks2-d7.*Kf))));
e8 = ((1-P1).*(1-P2));
G1 = (e2./e1);
G2 = (1./e1);
G3 = (e3./e1);
G4 = (e4./e1);
G5 = (1./e5);
G6 = (e6./e7);
G7 = (1./e7);
G8 = (1./e8);
dydx = @(x,y)[y(5);
y(6);
y(7);
y(8);
-(Nt.*Pr.*G6.*y(5))+(S1.*Pr.*G6.*y(1));
-(Nt.*Sc.*G8.*y(6))+(Hp.*Sc.*G8.*y(2));
-(Nt.*G1.*y(7))-(M1.*G2.*y(8))-(((2.*1i.*RO.*G1)-(1./k)).*y(3))-(GT.*G3.*y(1))-(GC.*G4.*y(2));
-((y(7)./((1+1i.*Hc).*G5)))-((Nt.*Pm.*y(8))./((1+1i.*Hc).*G5))];
BC1 = @(ya,yb)[(ya(5)-G7.*B1.*(ya(1)-1));yb(1);
(ya(6)-G8.*F1.*(ya(2)-1));yb(2);
ya(3)-1;yb(7);
ya(4)-1;yb(8)];
yinit = [0.1;0.1;0.1;0.1;0.1;0.1;0.1;0.1];
solinit = bvpinit(linspace(0,2,50),yinit);
options = bvpset(‘AbsTol’,1e-3,’RelTol’,1e-3,’stats’,’off’,’Nmax’,1000);
U1 = bvp4c(dydx,BC1,solinit,options);
I need to find the following
F = ((du/dy)-Nt*(d^2u/dy^2)) at y=0,J = -(i*(dh/dy)) at y=0,
N1 = -(dT/dy) at y=0, N2 = -(dC/dy) at y=0. %I have the following non-linear coupled ODE’S
%u"+(Nt*G1*u’)+(M1*G2*h’)+(R1*u)+(G3*GT*Theta)+(G4*GC*Phi)=0,
%(1+iHc)*G5*h"+u’+Nt*Pm*h’=0,
%T"+(Nt*Pr*G6)*T’-(S1*Pr*G7*T)=0;
%C"+(Nt*Sc*G8*C’)-(Hp*Sc*G8*C)=0;
% Boundary conditions: u=1, h=1,T’=G7*B1*(T-1),C’=G8*F1*(C-1) at y=0.
% u’,h’,T,C = 0 at y tends to infinity.
clc
B1 = 0.5;
F1 = 0.5;
k = 0.3;
RO = 0.5;
Hp = 0.2;
M1 = 16;
Nt = 0.15;
Pr = 6.2;
Pm = 0.7;
S1 = 1;
P1 = 0.02;
P2 = 0.0;
Sc = 0.78;
Hc = 0.5;
GT = 4;
GC = 5;
e1 = (1./(((1-P1).^2.5).*((1-P2).^2.5)));
Ros1 = 4420;
Ros2 = 5180;
Rof = 997.1;
Ro1 = (Ros1./Rof);
Ro2 = (Ros2./Rof);
e2 = ((1-P2).*((1-P1)+(P1.*Ro1)))+(P2.*Ro2);
Betas1 = 0.000058;
Betas2 = 0.000013;
Betaf = 0.00021;
Beta1 = ((Ros1.*Betas1)./(Rof.*Betaf));
Beta2 = ((Ros2.*Betas2)./(Rof.*Betaf));
e3 = ((1-P2).*((1-P1)+(P1.*Beta1)))+(P2.*Beta2);
BetaCs1 = 0.006;
BetaCs2 = 0.45;
BetaCf = 1;
BetaC1 = ((Ros1.*BetaCs1)./(Rof.*BetaCf));
BetaC2 = ((Ros2.*BetaCs2)./(Rof.*BetaCf));
e4 = ((1-P2).*((1-P1)+(P1.*BetaC1)))+(P2.*BetaC2);
sigmas1 = 580000;
sigmas2 = 25000;
sigmaf = 0.005;
sigma = (sigmas1./sigmaf);
d5 = (((1+2.*P1)+(2.*(1-P1).*(1./sigma)))./((1-P1)+((2+P1).*(1./sigma))));
e5 = d5.*(((sigmas2.*(1+2.*P2))+(2.*d5.*sigmaf.*(1-P2)))./((sigmas2.*(1-P2))+(d5.*sigmaf.*(2+P2))));
Cps1 = 0.56;
Cps2 = 670;
Cpf = 4179;
RoCp1 = ((Ros1.*Cps1)./(Rof.*Cpf));
RoCp2 = ((Ros2.*Cps2)./(Rof.*Cpf));
e6 = ((1-P2).*((1-P1)+(P1.*RoCp1)))+(P2.*RoCp2);
Ks1 = 7.2;
Ks2 = 9.7;
Kf = 0.613;
K = (Kf./Ks1);
d7 = (((1+2.*P1)+(2.*(1-P1).*K))./((1-P1)+((2+P1).*K)));
e7 = d7*((((Ks2+2.*d7.*Kf)+(2.*d7.*Kf))+(2.*P2.*(Ks2-d7.*Kf)))./((Ks2+2.*d7.*Kf)-(P2.*(Ks2-d7.*Kf))));
e8 = ((1-P1).*(1-P2));
G1 = (e2./e1);
G2 = (1./e1);
G3 = (e3./e1);
G4 = (e4./e1);
G5 = (1./e5);
G6 = (e6./e7);
G7 = (1./e7);
G8 = (1./e8);
dydx = @(x,y)[y(5);
y(6);
y(7);
y(8);
-(Nt.*Pr.*G6.*y(5))+(S1.*Pr.*G6.*y(1));
-(Nt.*Sc.*G8.*y(6))+(Hp.*Sc.*G8.*y(2));
-(Nt.*G1.*y(7))-(M1.*G2.*y(8))-(((2.*1i.*RO.*G1)-(1./k)).*y(3))-(GT.*G3.*y(1))-(GC.*G4.*y(2));
-((y(7)./((1+1i.*Hc).*G5)))-((Nt.*Pm.*y(8))./((1+1i.*Hc).*G5))];
BC1 = @(ya,yb)[(ya(5)-G7.*B1.*(ya(1)-1));yb(1);
(ya(6)-G8.*F1.*(ya(2)-1));yb(2);
ya(3)-1;yb(7);
ya(4)-1;yb(8)];
yinit = [0.1;0.1;0.1;0.1;0.1;0.1;0.1;0.1];
solinit = bvpinit(linspace(0,2,50),yinit);
options = bvpset(‘AbsTol’,1e-3,’RelTol’,1e-3,’stats’,’off’,’Nmax’,1000);
U1 = bvp4c(dydx,BC1,solinit,options);
I need to find the following
F = ((du/dy)-Nt*(d^2u/dy^2)) at y=0,J = -(i*(dh/dy)) at y=0,
N1 = -(dT/dy) at y=0, N2 = -(dC/dy) at y=0. how to get the answer from the following code. MATLAB Answers — New Questions
I am having trouble generating the correct trajectory for my robot.
Hi,
I am trying to get the Forward Kinematic (FK), the Inverse Kinematic (IK) and the Jacobian (J) for my closed loop robot. I have broken up the joints to create the rigidBodyTree. Here is my problem.
Originally, I used 4 sine wave generators to provide the movement to my actuated joints to perform the motion I would like it to. Then I fed it to the GetTransform block (GT) and padded the other non actuating joints as zero. This worked well and allow me visualise the motion of the robot. However, when I included the the trajectory from a signal editor, I cannot get my robot to perform the motion I want. The my desired motion is for the entired part of the robot to rotate around the x axis, and the end effector tip to pivot in an arc motion in the xy plane.
When I used the signal editor, the robot only moves and roll in the x axis, which is one of the movements. The other movements can’t be seen (i.e pivoting). I tried setting values for the signals in the signal editor to be higher (i.e at 1 it’s 20 instead of 5 and at 2 it’s 50 instead of 10) to see better movement and it worked. Problem is, it stills only rotate in the X axis. I’ve tried using the original sine wave generators (the ones with the values that allows me to have the desired movement) and feed it into a mux before feeding that connection into the Coordinate Transformation block to get a 4×4 Homogenous Transformation block before connecting it to the Pose port of IK. That still give me the same error. I also tried exporting the sine waves data as xls and then import them into the Signal Editor. That still gives me the same issue.
I then tried to visualise the movements of the end effector and hopefully get those values to be waypoints, hoping to control the robot better. I used the Transform Sensor and a couple of other To Workspace blocks to output the values for post processing. After the desired simulation and movement (I connected them to the model where my sine wave generators connect directly to the joints of the robot to give the desired movements), I had a script and post processed it. I got it to save into a variable called "mytraj". I connected that then to the model with the IK and it still gives me the error. I went into the variable itself and increases every values by timing it by 10 or 20 to see if anything will happen. And sure enough it did the same issue. Only rotation around the X axis, nothing else. The more I increase the value, the more degree or obvious it rotates around the X axis and nothing else. How can I please solve this issue?
This is the code for the waypoints from the visualisation:
X_positions = out.X.signals.values;
Y_positions = out.Y.signals.values;
Z_positions = out.Z.signals.values;
time = out.X.time; % Time vector
figure;
plot(X_positions, Z_positions, ‘color’, [60 100 175]/255);
xlabel(‘Y Coordinate (cm)’);
ylabel(‘Z Coordinate (cm)’);
grid on;
figure;
plot(X_positions, Y_positions, ‘color’, [60 100 175]/255);
xlabel(‘Y Coordinate (cm)’);
ylabel(‘Z Coordinate (cm)’);
grid on;
figure;
plot(Y_positions, Z_positions, ‘color’, [60 100 175]/255);
xlabel(‘Y Coordinate (cm)’);
ylabel(‘Z Coordinate (cm)’);
grid on;
figure;
plot(Z_positions, X_positions, ‘color’, [60 100 175]/255);
xlabel(‘Y Coordinate (cm)’);
ylabel(‘Z Coordinate (cm)’);
grid on;
figure;
plot(Y_positions, X_positions, ‘color’, [60 100 175]/255);
xlabel(‘Y Coordinate (cm)’);
ylabel(‘Z Coordinate (cm)’);
grid on;
figure;
plot(Z_positions, Y_positions, ‘color’, [60 100 175]/255);
xlabel(‘Y Coordinate (cm)’);
ylabel(‘Z Coordinate (cm)’);
grid on;
figure;
plot3(X_positions, Y_positions, Z_positions, ‘b’, ‘LineWidth’, 2);
xlabel(‘X Coordinate’);
ylabel(‘Y Coordinate’);
zlabel(‘Z Coordinate’);
title(‘End Effector Trajectory’);
grid on;
% Plot the full trajectory
figure;
plot3(X_positions, Y_positions, Z_positions, ‘b’, ‘LineWidth’, 2);
xlabel(‘X Coordinate’);
ylabel(‘Y Coordinate’);
zlabel(‘Z Coordinate’);
grid on;
hold on;
% Plot the waypoints
plot3(waypoints(:,1), waypoints(:,2), waypoints(:,3), ‘ro’, ‘MarkerSize’, 8);
title(‘End Effector Trajectory with Waypoints’);
hold off;
% Number of waypoints you want (e.g., 20)
num_waypoints = 20;
% Interpolate the time values from 0 to max time over the number of waypoints
waypoints_time = linspace(0, max(time), num_waypoints);
% Select waypoints from X, Y, and Z positions by downsampling
waypoint_indices = round(linspace(1, length(X_positions), num_waypoints)); % Get indices for waypoints
waypoints = [X_positions(waypoint_indices), Y_positions(waypoint_indices), Z_positions(waypoint_indices)];
% Combine interpolated time and waypoints to form the trajectory matrix
traj2ii = [waypoints_time’, waypoints];
trajectory_data = [time, X_positions, Y_positions, Z_positions];
My other question is: For now I have decided to connect the output config of FK to the pose of IK since output of FK is a 4×4 homogenous matrix. I directly control the joints of the robot with my sine wave generators. Is this a correct set up? Basically, sine generators to robot subsystem which connects to FK which connects to IK which is connected to the Jacobian block. Additionally, I have 4 actuated joints which I can clearly see are moving. However, my IK only shows 3 out of 11 joints values. It should be 4 since I am controlling and putting values to 4 joints. The other 7 are understandable since they’re non actuating and I have padded it with zeros.
I have attached all the appropriate figures in this post. Please help me with this.Hi,
I am trying to get the Forward Kinematic (FK), the Inverse Kinematic (IK) and the Jacobian (J) for my closed loop robot. I have broken up the joints to create the rigidBodyTree. Here is my problem.
Originally, I used 4 sine wave generators to provide the movement to my actuated joints to perform the motion I would like it to. Then I fed it to the GetTransform block (GT) and padded the other non actuating joints as zero. This worked well and allow me visualise the motion of the robot. However, when I included the the trajectory from a signal editor, I cannot get my robot to perform the motion I want. The my desired motion is for the entired part of the robot to rotate around the x axis, and the end effector tip to pivot in an arc motion in the xy plane.
When I used the signal editor, the robot only moves and roll in the x axis, which is one of the movements. The other movements can’t be seen (i.e pivoting). I tried setting values for the signals in the signal editor to be higher (i.e at 1 it’s 20 instead of 5 and at 2 it’s 50 instead of 10) to see better movement and it worked. Problem is, it stills only rotate in the X axis. I’ve tried using the original sine wave generators (the ones with the values that allows me to have the desired movement) and feed it into a mux before feeding that connection into the Coordinate Transformation block to get a 4×4 Homogenous Transformation block before connecting it to the Pose port of IK. That still give me the same error. I also tried exporting the sine waves data as xls and then import them into the Signal Editor. That still gives me the same issue.
I then tried to visualise the movements of the end effector and hopefully get those values to be waypoints, hoping to control the robot better. I used the Transform Sensor and a couple of other To Workspace blocks to output the values for post processing. After the desired simulation and movement (I connected them to the model where my sine wave generators connect directly to the joints of the robot to give the desired movements), I had a script and post processed it. I got it to save into a variable called "mytraj". I connected that then to the model with the IK and it still gives me the error. I went into the variable itself and increases every values by timing it by 10 or 20 to see if anything will happen. And sure enough it did the same issue. Only rotation around the X axis, nothing else. The more I increase the value, the more degree or obvious it rotates around the X axis and nothing else. How can I please solve this issue?
This is the code for the waypoints from the visualisation:
X_positions = out.X.signals.values;
Y_positions = out.Y.signals.values;
Z_positions = out.Z.signals.values;
time = out.X.time; % Time vector
figure;
plot(X_positions, Z_positions, ‘color’, [60 100 175]/255);
xlabel(‘Y Coordinate (cm)’);
ylabel(‘Z Coordinate (cm)’);
grid on;
figure;
plot(X_positions, Y_positions, ‘color’, [60 100 175]/255);
xlabel(‘Y Coordinate (cm)’);
ylabel(‘Z Coordinate (cm)’);
grid on;
figure;
plot(Y_positions, Z_positions, ‘color’, [60 100 175]/255);
xlabel(‘Y Coordinate (cm)’);
ylabel(‘Z Coordinate (cm)’);
grid on;
figure;
plot(Z_positions, X_positions, ‘color’, [60 100 175]/255);
xlabel(‘Y Coordinate (cm)’);
ylabel(‘Z Coordinate (cm)’);
grid on;
figure;
plot(Y_positions, X_positions, ‘color’, [60 100 175]/255);
xlabel(‘Y Coordinate (cm)’);
ylabel(‘Z Coordinate (cm)’);
grid on;
figure;
plot(Z_positions, Y_positions, ‘color’, [60 100 175]/255);
xlabel(‘Y Coordinate (cm)’);
ylabel(‘Z Coordinate (cm)’);
grid on;
figure;
plot3(X_positions, Y_positions, Z_positions, ‘b’, ‘LineWidth’, 2);
xlabel(‘X Coordinate’);
ylabel(‘Y Coordinate’);
zlabel(‘Z Coordinate’);
title(‘End Effector Trajectory’);
grid on;
% Plot the full trajectory
figure;
plot3(X_positions, Y_positions, Z_positions, ‘b’, ‘LineWidth’, 2);
xlabel(‘X Coordinate’);
ylabel(‘Y Coordinate’);
zlabel(‘Z Coordinate’);
grid on;
hold on;
% Plot the waypoints
plot3(waypoints(:,1), waypoints(:,2), waypoints(:,3), ‘ro’, ‘MarkerSize’, 8);
title(‘End Effector Trajectory with Waypoints’);
hold off;
% Number of waypoints you want (e.g., 20)
num_waypoints = 20;
% Interpolate the time values from 0 to max time over the number of waypoints
waypoints_time = linspace(0, max(time), num_waypoints);
% Select waypoints from X, Y, and Z positions by downsampling
waypoint_indices = round(linspace(1, length(X_positions), num_waypoints)); % Get indices for waypoints
waypoints = [X_positions(waypoint_indices), Y_positions(waypoint_indices), Z_positions(waypoint_indices)];
% Combine interpolated time and waypoints to form the trajectory matrix
traj2ii = [waypoints_time’, waypoints];
trajectory_data = [time, X_positions, Y_positions, Z_positions];
My other question is: For now I have decided to connect the output config of FK to the pose of IK since output of FK is a 4×4 homogenous matrix. I directly control the joints of the robot with my sine wave generators. Is this a correct set up? Basically, sine generators to robot subsystem which connects to FK which connects to IK which is connected to the Jacobian block. Additionally, I have 4 actuated joints which I can clearly see are moving. However, my IK only shows 3 out of 11 joints values. It should be 4 since I am controlling and putting values to 4 joints. The other 7 are understandable since they’re non actuating and I have padded it with zeros.
I have attached all the appropriate figures in this post. Please help me with this. Hi,
I am trying to get the Forward Kinematic (FK), the Inverse Kinematic (IK) and the Jacobian (J) for my closed loop robot. I have broken up the joints to create the rigidBodyTree. Here is my problem.
Originally, I used 4 sine wave generators to provide the movement to my actuated joints to perform the motion I would like it to. Then I fed it to the GetTransform block (GT) and padded the other non actuating joints as zero. This worked well and allow me visualise the motion of the robot. However, when I included the the trajectory from a signal editor, I cannot get my robot to perform the motion I want. The my desired motion is for the entired part of the robot to rotate around the x axis, and the end effector tip to pivot in an arc motion in the xy plane.
When I used the signal editor, the robot only moves and roll in the x axis, which is one of the movements. The other movements can’t be seen (i.e pivoting). I tried setting values for the signals in the signal editor to be higher (i.e at 1 it’s 20 instead of 5 and at 2 it’s 50 instead of 10) to see better movement and it worked. Problem is, it stills only rotate in the X axis. I’ve tried using the original sine wave generators (the ones with the values that allows me to have the desired movement) and feed it into a mux before feeding that connection into the Coordinate Transformation block to get a 4×4 Homogenous Transformation block before connecting it to the Pose port of IK. That still give me the same error. I also tried exporting the sine waves data as xls and then import them into the Signal Editor. That still gives me the same issue.
I then tried to visualise the movements of the end effector and hopefully get those values to be waypoints, hoping to control the robot better. I used the Transform Sensor and a couple of other To Workspace blocks to output the values for post processing. After the desired simulation and movement (I connected them to the model where my sine wave generators connect directly to the joints of the robot to give the desired movements), I had a script and post processed it. I got it to save into a variable called "mytraj". I connected that then to the model with the IK and it still gives me the error. I went into the variable itself and increases every values by timing it by 10 or 20 to see if anything will happen. And sure enough it did the same issue. Only rotation around the X axis, nothing else. The more I increase the value, the more degree or obvious it rotates around the X axis and nothing else. How can I please solve this issue?
This is the code for the waypoints from the visualisation:
X_positions = out.X.signals.values;
Y_positions = out.Y.signals.values;
Z_positions = out.Z.signals.values;
time = out.X.time; % Time vector
figure;
plot(X_positions, Z_positions, ‘color’, [60 100 175]/255);
xlabel(‘Y Coordinate (cm)’);
ylabel(‘Z Coordinate (cm)’);
grid on;
figure;
plot(X_positions, Y_positions, ‘color’, [60 100 175]/255);
xlabel(‘Y Coordinate (cm)’);
ylabel(‘Z Coordinate (cm)’);
grid on;
figure;
plot(Y_positions, Z_positions, ‘color’, [60 100 175]/255);
xlabel(‘Y Coordinate (cm)’);
ylabel(‘Z Coordinate (cm)’);
grid on;
figure;
plot(Z_positions, X_positions, ‘color’, [60 100 175]/255);
xlabel(‘Y Coordinate (cm)’);
ylabel(‘Z Coordinate (cm)’);
grid on;
figure;
plot(Y_positions, X_positions, ‘color’, [60 100 175]/255);
xlabel(‘Y Coordinate (cm)’);
ylabel(‘Z Coordinate (cm)’);
grid on;
figure;
plot(Z_positions, Y_positions, ‘color’, [60 100 175]/255);
xlabel(‘Y Coordinate (cm)’);
ylabel(‘Z Coordinate (cm)’);
grid on;
figure;
plot3(X_positions, Y_positions, Z_positions, ‘b’, ‘LineWidth’, 2);
xlabel(‘X Coordinate’);
ylabel(‘Y Coordinate’);
zlabel(‘Z Coordinate’);
title(‘End Effector Trajectory’);
grid on;
% Plot the full trajectory
figure;
plot3(X_positions, Y_positions, Z_positions, ‘b’, ‘LineWidth’, 2);
xlabel(‘X Coordinate’);
ylabel(‘Y Coordinate’);
zlabel(‘Z Coordinate’);
grid on;
hold on;
% Plot the waypoints
plot3(waypoints(:,1), waypoints(:,2), waypoints(:,3), ‘ro’, ‘MarkerSize’, 8);
title(‘End Effector Trajectory with Waypoints’);
hold off;
% Number of waypoints you want (e.g., 20)
num_waypoints = 20;
% Interpolate the time values from 0 to max time over the number of waypoints
waypoints_time = linspace(0, max(time), num_waypoints);
% Select waypoints from X, Y, and Z positions by downsampling
waypoint_indices = round(linspace(1, length(X_positions), num_waypoints)); % Get indices for waypoints
waypoints = [X_positions(waypoint_indices), Y_positions(waypoint_indices), Z_positions(waypoint_indices)];
% Combine interpolated time and waypoints to form the trajectory matrix
traj2ii = [waypoints_time’, waypoints];
trajectory_data = [time, X_positions, Y_positions, Z_positions];
My other question is: For now I have decided to connect the output config of FK to the pose of IK since output of FK is a 4×4 homogenous matrix. I directly control the joints of the robot with my sine wave generators. Is this a correct set up? Basically, sine generators to robot subsystem which connects to FK which connects to IK which is connected to the Jacobian block. Additionally, I have 4 actuated joints which I can clearly see are moving. However, my IK only shows 3 out of 11 joints values. It should be 4 since I am controlling and putting values to 4 joints. The other 7 are understandable since they’re non actuating and I have padded it with zeros.
I have attached all the appropriate figures in this post. Please help me with this. robotic system toolbox, robot, simulink, matlab, waypoints, trajectories, signal editor, from workspace, to workspace, desired movement MATLAB Answers — New Questions
why is the Transfer fcn like this instead of showing in variable s?
Post Content Post Content simulink, transfer function MATLAB Answers — New Questions
Explicit method for Allen-Cahn equation
The plot of the equation must start at x=-1 and end at x=1. but mu result did not show that?
clear all;
clc;
maxk = 1000;
T = 0.10;
n = 50;
L = 2; % Length of the spatial domain [−1, 1]
Nx = 400; % Number of spatial grid points
dx = L / (Nx – 1); % Spatial step size
dt = T/maxk;
T = 1; % Final time
Nt = round(T / dt); % Number of time steps
a = 0.0001;
r = a * dt / (dx * dx); % Diffusion factor for explicit scheme
% Initial condition
x = linspace(-1, 1, n+1);
u = zeros(n+1, maxk+1);
u(:,1) = x.^2 .* cos(pi * x);
% Implementation of the explicit method for Allen-Cahn equation
for t = 1:maxk
% Internal points
for i = 2:n
u(i, t+1) = u(i, t) + r * (u(i-1, t) – 2 * u(i, t) + u(i+1, t)) …
+ dt * (5 * u(i, t)^3 – 5 * u(i, t));
end
% Periodic boundary conditions
u(1, t+1) = u(end-1, t+1); % Periodic condition for first point
u(end, t+1) = u(2, t+1); % Periodic condition for last point
end
% Plot results
figure; % Create a new figure
xx = linspace(-1, 1, 100);
t_values = [0, 0.2, 0.4, 0.6, 0.8]; % Time values to plot
plot(x, u(:,1), ‘-‘, x, u(:,round(maxk*0.2)), ‘-‘, x, u(:,round(maxk*0.4)), ‘-‘, x, u(:,round(maxk*0.6)), ‘-‘, x, u(:,end), ‘-‘);
xlabel(‘x’);
ylabel(‘u(x,t)’);
grid on;
legend(‘t = 0’, ‘t = 0.2’, ‘t = 0.4’, ‘t = 0.6’, ‘t = 0.8’);
hold off;The plot of the equation must start at x=-1 and end at x=1. but mu result did not show that?
clear all;
clc;
maxk = 1000;
T = 0.10;
n = 50;
L = 2; % Length of the spatial domain [−1, 1]
Nx = 400; % Number of spatial grid points
dx = L / (Nx – 1); % Spatial step size
dt = T/maxk;
T = 1; % Final time
Nt = round(T / dt); % Number of time steps
a = 0.0001;
r = a * dt / (dx * dx); % Diffusion factor for explicit scheme
% Initial condition
x = linspace(-1, 1, n+1);
u = zeros(n+1, maxk+1);
u(:,1) = x.^2 .* cos(pi * x);
% Implementation of the explicit method for Allen-Cahn equation
for t = 1:maxk
% Internal points
for i = 2:n
u(i, t+1) = u(i, t) + r * (u(i-1, t) – 2 * u(i, t) + u(i+1, t)) …
+ dt * (5 * u(i, t)^3 – 5 * u(i, t));
end
% Periodic boundary conditions
u(1, t+1) = u(end-1, t+1); % Periodic condition for first point
u(end, t+1) = u(2, t+1); % Periodic condition for last point
end
% Plot results
figure; % Create a new figure
xx = linspace(-1, 1, 100);
t_values = [0, 0.2, 0.4, 0.6, 0.8]; % Time values to plot
plot(x, u(:,1), ‘-‘, x, u(:,round(maxk*0.2)), ‘-‘, x, u(:,round(maxk*0.4)), ‘-‘, x, u(:,round(maxk*0.6)), ‘-‘, x, u(:,end), ‘-‘);
xlabel(‘x’);
ylabel(‘u(x,t)’);
grid on;
legend(‘t = 0’, ‘t = 0.2’, ‘t = 0.4’, ‘t = 0.6’, ‘t = 0.8’);
hold off; The plot of the equation must start at x=-1 and end at x=1. but mu result did not show that?
clear all;
clc;
maxk = 1000;
T = 0.10;
n = 50;
L = 2; % Length of the spatial domain [−1, 1]
Nx = 400; % Number of spatial grid points
dx = L / (Nx – 1); % Spatial step size
dt = T/maxk;
T = 1; % Final time
Nt = round(T / dt); % Number of time steps
a = 0.0001;
r = a * dt / (dx * dx); % Diffusion factor for explicit scheme
% Initial condition
x = linspace(-1, 1, n+1);
u = zeros(n+1, maxk+1);
u(:,1) = x.^2 .* cos(pi * x);
% Implementation of the explicit method for Allen-Cahn equation
for t = 1:maxk
% Internal points
for i = 2:n
u(i, t+1) = u(i, t) + r * (u(i-1, t) – 2 * u(i, t) + u(i+1, t)) …
+ dt * (5 * u(i, t)^3 – 5 * u(i, t));
end
% Periodic boundary conditions
u(1, t+1) = u(end-1, t+1); % Periodic condition for first point
u(end, t+1) = u(2, t+1); % Periodic condition for last point
end
% Plot results
figure; % Create a new figure
xx = linspace(-1, 1, 100);
t_values = [0, 0.2, 0.4, 0.6, 0.8]; % Time values to plot
plot(x, u(:,1), ‘-‘, x, u(:,round(maxk*0.2)), ‘-‘, x, u(:,round(maxk*0.4)), ‘-‘, x, u(:,round(maxk*0.6)), ‘-‘, x, u(:,end), ‘-‘);
xlabel(‘x’);
ylabel(‘u(x,t)’);
grid on;
legend(‘t = 0’, ‘t = 0.2’, ‘t = 0.4’, ‘t = 0.6’, ‘t = 0.8’);
hold off; allen cahn equation, nonlinear MATLAB Answers — New Questions